June 2018
Beginner
722 pages
18h 47m
English
To be fair, there are ways to create an immutable collection even without using the of() factory methods. Here is one way to do it:
List<String> iList = Collections.unmodifiableList(new ArrayList<>() {{ add("s1"); add("s1"); }});//iList.set(0, "s0"); //UnsupportedOperationException//iList.add("s2"); //UnsupportedOperationExceptionSystem.out.println(iList); //prints: [s1, s1]
The trick is not to have a reference to the original collection (the source of values) used to create the unmodifiable collection, so it cannot be used to change the underlying source.
And here is another way to create an immutable collection without using the of() factory methods:
String[] source = {"s1", "s2"};List<String> ...Read now
Unlock full access