By looking at the code of Collections
class, i got to know that when we are using the method unmodifiableList(List list)
or unmodifiableCollection(Collection c)
it is not creating a new object but it is returning the reference of the same object and overriding the methods which can modify the List
[ add
, addall
, remove
, retainAll
... ]
So i ran this test:
List modifiableList = new ArrayList();
modifiableList.add ( 1 );
List unmodifiableList = Collections.unmodifiableList( modifiableList );
// unmodifiableList.add(3); // it will throw the exception
modifiableList.add ( 2 );
System.out.println( unmodifiableList );
result is [ 1,2 ]
.
Now the point is why it is referring to the same object? Why it don't create a new object?