Wednesday, May 13, 2015

Create immutable class in java

Immutable class is a class which once created , its content cannot be changed.Immutable Object are the objects whose state cannot be changed once constructed. e.g. String.
All wrapper class in java.lang are immutable - String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

Since the state of immutable object can not be changed once they are created, they are automatically thread safe/synchronized.

In order to create an immutable class, following steps should be followed

  1. Create a final class - no other class can not inherit immutable
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private.
  4. Do not provide any setters for these properties.
  5. If the instance fields include reference variable to mutable object, don't allow those object to be changed.
E.g.
public final class MyImmutableClass{

private final String name;
private final int age;
private final Date mutableField;

public MyImmutableClass(final String name, final int age; Date mutableField){

super();
this.name = name;
this.age = age;
this.mutableField = mutableField;
}

public int getAge(){
return age;
}

public String getName(){
return name;
}

public Date getMutableField() {
        return new Date(mutableField.getTime());
    }

public String toString() {
        return name +" - "+ age +" - "+ mutableField ;
    }
}

Wednesday, May 6, 2015

Convert java array to collection list and vice versa

List and Set classes have toArray() method and Arrays class has toList() method.
Array.asList() copies array to List.

Below line of code convert Array object to List object.
String[] oa = new String[];
List cList = Arrays.asList(oa);


Below line of code convert List to Array object.
List cList = new ArrayList();
Object[] oa = cList.toArray();