Immutable Collections Vs Unmodifiable Collections in Java

Unmodifiable Collection is kind of collection which is readonly view of Collections. You can not do modification into this kind of collections. They always present Latest Value. If any of source collection changes then unmodifiable collection contains those changes.

While Immutable Collections are such kind of Collection which is readonly copy of Collections. They can not be modified. if any of source collection changes then immutable collections will not reflect with changes.


Java Program to demonstrate Unmodifiable and Modifiable Collections
package com.anuj.collections;

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

/**
 *
 * @author Anuj
 *
 */
public class UnmodifiableCollection {

    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("a");
        sourceList.add("b");
        sourceList.add("c");
        System.out.println("sourceList - " + sourceList);

        List<String> unModifiableList = Collections.unmodifiableList(sourceList);
        System.out.println("unmodifiableList - " + unModifiableList);

        System.out.println("----After Adding Data into SourceList----");
        sourceList.add("e");
        try {
            unModifiableList.add("d");
        } catch (UnsupportedOperationException e) {
            System.out.println("Can not add 'd' to unModifiableList");
        }
        System.out.println("sourceList - " + sourceList);
        System.out.println("unModifiableList - " + unModifiableList);

        System.out.println("----After Adding Data into SourceList----");
        List<String> immutableList = Collections.unmodifiableList(new ArrayList<String>(sourceList));
        sourceList.add("f");
        try {
            immutableList.add("g");
        } catch (UnsupportedOperationException e) {
            System.out.println("Can not add 'g' to immutable List");
        }
        System.out.println("sourceList - " + sourceList);
        System.out.println("unModifiableList - " + unModifiableList);
        System.out.println("immutableList - " + immutableList);
    }
}


Output :
run:
sourceList - [a, b, c]
unmodifiableList - [a, b, c]

----After Adding Data into SourceList----
Can not add 'd' to unModifiableList
sourceList - [a, b, c, e]
unModifiableList - [a, b, c, e]

----After Adding Data into SourceList----
Can not add 'g' to immutable List
sourceList - [a, b, c, e, f]
unModifiableList - [a, b, c, e, f]
immutableList - [a, b, c, e]

No comments:

Post a Comment