Reputation: 595
As per comment of Collections.emptyList()
method
it returns an empty immutable list.
It is justified if we do direct assignment to the object. Example:
public class ImmutableList {
public static void main(String[] args){
List<String> namesList=Collections.emptyList();
String[] names = {"Name1", "Name2", "Name3"};
namesList.addAll(Arrays.asList(names));
}
private List<String> getList() {
String[] names = {"Name1", "Name2", "Name3"};
return Arrays.asList(names);
}
}
If we run the above program, it throws following exception
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
at org.learn.list.ImmutableList.main(ImmutableList.java:11)
However, if we assign the output of a method to this variable, then it runs fine. Example:
public class ImmutableListTest2 {
public static void main(String[] args){
List<String> namesList=Collections.emptyList();
ImmutableListTest2 ce = new ImmutableListTest2();
namesList = ce.getList();
namesList.forEach(System.out::print);
}
private List<String> getList() {
String[] names = {"Name1", "Name2", "Name3"};
return Arrays.asList(names);
}
}
Ouput:
Name1Name2Name3
My question is namesList should be immutable in any case. Why we are able to mutate this variable in second case.
It should throw UnsupportedOperationException
in all cases.
Any help is appreciated. Thanks!
Upvotes: 1
Views: 79
Reputation: 393781
namesList
is not immutable. The original List<String>
that it referenced (returned by Collections.emptyList()
) is immutable.
namesList
is a variable of List<String>
type. Hence you can assign to it a reference to any List<String>
instance, mutable or not. When you assign to it the List
returned by ce.getList()
, it no longer references an immutable List
.
If you want to prevent that, make it a final
variable, which will prevent it from being re-assigned:
final List<String> namesList=Collections.emptyList();
Upvotes: 6