Ad

Saturday 6 September 2014

Collections algorithm - rotate,frequency,min,max and disjoint with sample program

In the post "Collections algorithm" we have seen about the algorithms reverse,shuffle,swap,fill and replace available in Collections class. Here we will see about the below remaining algorithm available in java.util.Collections.
  • rotate - This static method will rotate the specified list forward or backward by a specified distance.To move the list forward provide the distance as positive integer and to move backward provide the distance as negative integer.
  • frequency- This static method will return the count of the specified element exist in the specified list.
  • min- This static method will return the minimum element of the specified list according to the natural ordering of the element in the list.
  • max  - This static method will return the maximum element of the specified list according to the natural ordering of the element in the list.
  • disjoint - This static method will return true, if the two specified collection has no common elements between them.It will return false, if there is any common element between them.
Below sample program will illustrate how these methods can be used.

import java.util.ArrayList;                                                                                                                           
import java.util.Collections;
import java.util.List;

public class CollectionsSample {

public static void main(String[] args) {
CollectionsSample collectionsSample= new CollectionsSample();
collectionsSample.rotate();
collectionsSample.frequency();
collectionsSample.min();
collectionsSample.max();
collectionsSample.disjoint();
}

private void rotate() {
List<String> list=initializeList();
System.out.println("Values in the list before rotating:"+list);
Collections.rotate(list,1);
System.out.println("Values in the list after rotating forward by 1 position:"+list+"\n");
list=initializeList();
System.out.println("Values in the list before rotating:"+list);
Collections.rotate(list,-1);
System.out.println("Values in the list after roating backward by 1 position:"+list+"\n");
}
private void frequency() {
List<String> list=initializeList();
System.out.println("Values in the list :"+list);
int count =Collections.frequency(list, "HYUNDAI");
System.out.println("Number of Hyundai element in the list:"+count+"\n");
}
private void min() {
List<String> list=initializeList();
System.out.println("Values in the list:"+list);
String minElement=Collections.min(list);
System.out.println("Minimum element in the list is:"+minElement+"\n");
}

private void max() {
List<String> list=initializeList();
System.out.println("Values in the list:"+list);
String maxElement=Collections.max(list);
System.out.println("Maximum element in the list is:"+maxElement+"\n");
}
private void disjoint() {
List<String> list=initializeList();
List<String> secondList=new ArrayList<String>();
secondList.add("RENUALT");
secondList.add("AUDI");
System.out.println("Values in the first list :"+list);
System.out.println("Values in the second List :"+secondList);
boolean isDisjointList=Collections.disjoint(list, secondList);
if(isDisjointList)
{
 System.out.println("Above two list does not have any elements in common");
}
else
{
System.out.println("Above two list have some elements in common");  
}
}
private List<String> initializeList()
{
List<String> list= new ArrayList<String>();
list.add("HYUNDAI");
list.add("FORD");
list.add("HYUNDAI");
list.add("ZEN");
list.add("MARUTHI");
return list;
}
}

OUTPUT:

Values in the list before rotating:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Values in the list after rotating forward by 1 position:[MARUTHI, HYUNDAI, FORD, HYUNDAI, ZEN]

Values in the list before rotating:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Values in the list after roating backward by 1 position:[FORD, HYUNDAI, ZEN, MARUTHI, HYUNDAI]

Values in the list :[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Number of Hyundai element in the list:2

Values in the list:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Minimum element in the list is:FORD

Values in the list:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Maximum element in the list is:ZEN

Values in the first list :[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Values in the second List :[RENUALT, AUDI]
Above two list does not have any elements in common

Friday 5 September 2014

Collections algorithm - reverse,shuffle,swap,fill and replace with sample program

There are many algorithm available in java.util.Collections class which provides many static util methods.
All these method take one of the argument as the list or the collection where the algorithm need to be applied. Some of them are:
  • reverse    - This static method will reverse the order of the specified list.
  • swap         - This static method will swap the elements at the specified positions of the  list.
  • shuffle      - This static method will reorders all the elements in the list randomly.
  • fill             - This static method will fill/replace all the elements in the list with a specified value.
  • replaceAll- This static method will replace all the occurrence of one specified value in the list with                           another value
Below sample program will illustrate how these methods can be used.

import java.util.ArrayList;                                                                                                                          
import java.util.Collections;
import java.util.List;

public class CollectionsSample {

public static void main(String[] args) {
CollectionsSample collectionsSample= new CollectionsSample();
collectionsSample.reverse();
collectionsSample.swap();
collectionsSample.shuffle();
collectionsSample.fill();
collectionsSample.replace();
}

private void reverse() {
List<String> list=initializeList();
System.out.println("Values in List before reverse:"+list);
Collections.reverse(list);
System.out.println("Values in List after reverse:"+list);
System.out.println();
}
private void swap() {
List<String> list=initializeList();
System.out.println("Values in List before swap:"+list);
Collections.swap(list,1,3);
System.out.println("Values in List after swap:"+list);
System.out.println();
}
private void shuffle() {
List<String> list=initializeList();
System.out.println("Values in List before shuffle:"+list);
Collections.shuffle(list);
System.out.println("Values in List after shuffle:"+list);
System.out.println();
}

private void fill() {
List<String> list=initializeList();
System.out.println("Values in List before fill:"+list);
Collections.fill(list,"NA");
System.out.println("Values in List after fill:"+list);
System.out.println();
}
private void replace() {
List<String> list=initializeList();
System.out.println("Values in List before replace:"+list);
Collections.replaceAll(list,"Tennis","TableTennis");
System.out.println("Values in List after replace:"+list);
System.out.println();
}
private List<String> initializeList()
{
List<String> list= new ArrayList<String>();
list.add("Cricket");
list.add("Footbal");
list.add("Tennis");
list.add("Baseball");
return list;
}
}

Output:

Values in List before reverse:[Cricket, Footbal, Tennis, Baseball]
Values in List after reverse:[Baseball, Tennis, Footbal, Cricket]

Values in List before swap:[Cricket, Footbal, Tennis, Baseball]
Values in List after swap:[Cricket, Baseball, Tennis, Footbal]

Values in List before shuffle:[Cricket, Footbal, Tennis, Baseball]
Values in List after shuffle:[Tennis, Footbal, Cricket, Baseball]

Values in List before fill:[Cricket, Footbal, Tennis, Baseball]
Values in List after fill:[NA, NA, NA, NA]

Values in List before replace:[Cricket, Footbal, Tennis, Baseball]
Values in List after replace:[Cricket, Footbal, TableTennis, Baseball]

Thursday 4 September 2014

To secure and protect the sensitive information in serializable object

By using serialization we can save the  object state to the stream and we can  construct the saved object back from the stream when needed.Sometime we need to secure some attributes in our object to not to  get serialized i.e not to save its value.Consider the below code example where we are writing the StudentVo object to the file and reading back from it.

StudentVO.Java

import java.io.Serializable;                                                                                                                    

public class StudentVO implements Serializable {

private String loginId;

private  String password;

private String fullName;

private int age;

public StudentVO(String loginId, String password, String fullName,
int age) {
super();
this.loginId = loginId;
this.password = password;
this.fullName = fullName;
this.age = age;
}

@Override
public String toString() {
return "StudentVO [loginId=" + loginId + ", password=" + password
+ ", fullName=" + fullName + ", age=" + age + "]";
}
}

SerializerSample.java

import java.io.FileInputStream;                                                                                                              
import java.io.FileOutputStream;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializerSample {

private final static String  FILE_NAME="D:/objfile";

public static void main(String[] args) {
      StudentVO studentVO = new StudentVO("V01", "pwd", "John Peter", 20);
      SerializerSample serializerSample= new SerializerSample();
      serializerSample.serialize(studentVO);
      studentVO=serializerSample.deSerialize();
      System.out.println("Object deserialized from file is:"+studentVO.toString());
}

private void serialize(StudentVO  studentVO)
{
try {
    FileOutputStream fileOutputStream= new FileOutputStream(FILE_NAME);
      ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(studentVO);
   fileOutputStream.close();
   objectOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private StudentVO deSerialize()
{
StudentVO studentVO=null;
try
{
FileInputStream fileInputStream= new FileInputStream(FILE_NAME);
ObjectInputStream objectInputStream= new ObjectInputStream(fileInputStream);
studentVO=(StudentVO) objectInputStream.readObject();
   fileInputStream.close();
   objectInputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
return studentVO;
}
}

As we can see in the Class SerializerSample,first we will  write the object state to the file(in method serialize()) and then construct the object back from the file(in method deSerialize()).
When we run the program,we will get the below output:

Object deserialized from file is:StudentVO [loginId=V01, password=pwd, fullName=John Peter, age=20]

Since the password is an sensitive attribute,we should not save its value when serilaized into the file.
There are three ways to secure a serializable object
  1. Declaring the sensitive field as transient
  2. Declaring the field serialPersistentFields
  3. Defining writeObject and readObject methods
1)Declaring the sensitive field as transient

values for the attributes which are declared as transient will not be saved when the object is serialized.So declare the field password as transient in StudentVO as shown below,so that its state will not be saved.

private transient String password;                                                                                                              

2)Declaring the field serialPersistentFields

we can define the serializable fields that need to be saved using the attribute serialPersistentFields in the serializable class.This field should be initialized with an array of ObjectStreamField as shown below.

import java.io.ObjectStreamField;                                                                                                            
import java.io.Serializable;

public class StudentVO implements Serializable {
private String loginId;
private  String password;
private String fullName;
private int age;

private static final ObjectStreamField[] serialPersistentFields
 = {new ObjectStreamField("loginId", String.class),
      new ObjectStreamField("fullName", String.class),
      new ObjectStreamField("age",Integer.TYPE)};

public StudentVO(String loginId, String password, String fullName,
int age) {
super();
this.loginId = loginId;
this.password = password;
this.fullName = fullName;
this.age = age;
}

@Override
public String toString() {
return "StudentVO [loginId=" + loginId + ", password=" + password
+ ", fullName=" + fullName + ", age=" + age + "]";
}
}


We have defined only the fields loginid,fullName and age in the serialPersistentFields so that only this fields will be saved to the file on serialization and not the password field.

3)Defining writeObject and readObject methods in the Serializable Class

We can define the methods writeObject and readObject in the serializable class to control what information to be saved and to be retrieved back from the stream.

import java.io.IOException;                                                                                                                      
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class StudentVO implements Serializable {
private String loginId;
private  String password;
private String fullName;
private int age;
 public StudentVO(String loginId, String password, String fullName,
int age) {
super();
this.loginId = loginId;
this.password = password;
this.fullName = fullName;
this.age = age;
}

 private void readObject(ObjectInputStream ois) throws IOException,                                          
 ClassNotFoundException {
loginId=(String) ois.readObject();
fullName=(String) ois.readObject();
age=ois.readInt();
}
 private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.writeObject(loginId);
    oos.writeObject(fullName);
    oos.writeInt(age);
 }

@Override
public String toString() {
return "StudentVO [loginId=" + loginId + ", password=" + password
+ ", fullName=" + fullName + ", age=" + age + "]";
}
}

When the StudentVo object is serialized using writeObject method of the objectOutputStream,it will delegate the call to the method writeObject in serializable class StudentVO class.Thus only the fields loginId,fullName and age will be saved and not the password field.

OUTPUT:

When we run the SerializerSample class by using any of the above 3 versions of the StudentVO,we will get the below output

Object deserialized from file is:StudentVO [loginId=V01, password=null, fullName=John Peter, age=20]

As we can see in the output, the password field value was not saved during serialization.