Java : Immutable Class/Collection Creation


What is Mutable/Immutable Class?

A class is called as immutable class once object is created , we can not change it’s fields/objects values. If values are changeable then it’s mutable class.

Designing Rule

Classes should be immutable unless there’s a very good reason to make them mutable….
If a class cannot be made immutable, limit its mutability as much as possible.

In java all the wrapper classes and String class is immutable. For Ex: immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.

How to make a class Immutable Class?

Below are step by step guide to make a class Immutable:

Step 1 : Don’t provide “setter” methods that modify fields or objects referred to by fields.
Step 2 : Make all fields final and private.
Step 3 : Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Step 4 : If the instance fields include references to mutable objects, don’t allow those objects to be changed: Don’t provide methods that modify the mutable objects.
Step 5 : Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor.
If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

What are Benefits of Immutable Object?

  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. Immutable objects internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.

How to create Immutable Lists, Sets or Maps?

In JAVA 8 added “unmodifiable” method and JAVA 9 added “of” factory method to make collections like lists, sets and maps as immutable.  for example :

JAVA 8


Unmodifiable List
List stringList = Arrays.asList("Facing", "Issues", "On", "IT");
stringList = Collections.unmodifiableList(stringList);

Unmodifiable Set
Set stringSet = new HashSet<>(Arrays.asList("Facing", "Issues", "On", "IT"));
stringSet = Collections.unmodifiableSet(stringSet);

Unmodifiable Map
Map<String,Integer> stringMap = new HashMap<String, Integer>();
stringMap.put("Facing",1);
stringMap.put("Issues",2);
stringMap.put("On",3);
stringMap.put("IT",4);
stringMap = Collections.unmodifiableMap(stringMap);

JAVA 9


Unmodifiable List
List stringList = List.of("Facing", "Issues", "On", "IT");
Unmodifiable Set
Set stringSet = Set.of("Facing", "Issues", "On", "IT");

Unmodifiable Map
Map stringMap = Map.of("Facing",1, "Issues",2, "On",3, "IT",4);

 

Immutable Class Example


//make class final so that method not override
public final class ImmutableClass {
	final String pancardNumber;
	final String aadharNumber;
	final DOB dob;

	// Create object
	public ImmutableClass(String pancardNumber, String aadharNumber, DOB dob) {
		this.pancardNumber = pancardNumber;
		this.aadharNumber = aadharNumber;
		this.dob = dob;
	}
    //No setter method so that no fields get modifiable
	public String getPancardNumber() {
		return pancardNumber;
	}

	public String getAadharNumber() {
		return aadharNumber;
	}

	@Override
	public String toString() {
		return "ImmutableClass [pancardNumber=" + pancardNumber + ", aadharNumber=" + aadharNumber + ", dob=" + dob
				+ "]";
	}
}
public class  DOB {
	private int day;
	private int month;
	private int year;
	public DOB(int day, int month, int year)
	{
	this.day=day;
	this.month=month;
	this.year=year;
	}

	public int getDay() {
		return day;
	}

	public int getMonth() {
		return month;
	}

	public int getYear() {
		return year;
	}

	@Override
	public String toString() {
		return "DOB [day=" + day + ", month=" + month + ", year=" + year + "]";
	}

}
public class ImmuTableClassTest {

	public static void main(String[] args) {
		DOB dob = new DOB(24, 04, 1992);
		ImmutableClass immutableClass = new ImmutableClass("ABCD12345", "1234567890123456", dob);
		System.out.println(immutableClass);

	}

}

Output


ImmutableClass [pancardNumber=ABCD12345, aadharNumber=1234567890123456, dob=DOB [day=24, month=4, year=1992]]

Conclusion

In this blog you understand below points:

  • What is mutable and Immutable classes?
  • How make a class Immutable?
  • How to make collections like Lists, Sets and maps  immutable by Java 8 and Java 9?
  • Immutable class example.

References

https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s