I would like to feel the "magic power" of the copyOf() method for Guava guava-libraries .
There is a small application that I use to test it.
Here is the documentation :
The JDK provides Collections.unmodifiableXXX methods, but in our opinion, it could be
- bulky and verbose; unpleasant to use wherever you want to make protective copies.
- unsafe: returned collections are truly immutable if no one references the original collection
So, I'm trying to build a model where "someone holds a reference to the original collection" . Thus, when working with a copy of the collection, I should not worry about changing the cost of the copy. But magic does not work yet (there are two attempts: 1. copyOf(collection) , 2. copyOf(iterator) ):
import com.google.common.collect.ImmutableList; import java.util.LinkedList; import java.util.List; class MyObject { String name; public MyObject(String name) {this.name = name;} @Override public String toString() { return name; } } public class ListUnsafe { List<MyObject> list = new LinkedList<MyObject>(); { list.add(new MyObject("a")); list.add(new MyObject("b")); list.add(new MyObject("c")); } public List<MyObject> getList() { return ImmutableList.copyOf(list); } public List<MyObject> getCopyIterator() { return ImmutableList.copyOf(list.iterator()); } public static void main(String[] args) { ListUnsafe obj = new ListUnsafe(); { MyObject ref = obj.list.get(0); List<MyObject> myList = obj.getList(); MyObject copyObj = myList.get(0); copyObj.name = "new"; System.out.println("ref: " + ref); } obj = new ListUnsafe(); { MyObject ref = obj.list.get(0); List<MyObject> myList = obj.getCopyIterator(); MyObject copyObj = myList.iterator().next(); copyObj.name = "new"; System.out.println("ref: " + ref); } } }
Output:
ref: new ref: new
This means that we have changed the source data. What we did not want.
Question
Why doesn't he copy?
How is it different from unmodifiableXXX ?
There is a link to a similar question:
The answer says about copyOf :
- (from source)
copyOf(collection) instance does not create temporary ArrayList ( copyOf(Iterable) and copyOf(iterator) do this).
source share