Suppose I have the following Set
Set<String> fruits = new HashSet<String>();
fruits.add("Apple")
fruits.add("Grapes")
fruits.add("Orange")
If I wanted to create a defensive copy, so that if the original list is modified, the copy doesn't reflect it, I can do this:
Set<String> unmodifiableFruits = Collections.unmodifiableSet(new HashSet(fruits))
so if I do this:
fruits.add("Pineapple")
println(unmodifiableFruits)
unmodifiableFruits
won't have pineapple.
or I can so this:
Set<String> unmodifiableFruits = Collections.unmodifiableCollection(fruits)
and the result is the same, unmodifiableFruits
won't have pineapple.
Questions:
- Suppose if I were passing
fruits
as an argument to a class, is the preferred method theCollections.unmodifiableCollection()
?
The reason is, I've read that declaring new
in the constructor is a bad practice, if I were to use Collections.unmodifiableSet()
, I would need to declare a new HashSet<String>(fruits)
.
Why can't I do this ?
Collections.unmodifiableSet(fruits)
and have it return an unmodifiable collection.
instead I have to do this:
Collections.unmodifiableSet(new HashSet<String>(fruits))
Is it because Set is an interface and it doesn't know which implementation to return?