Collections.unmodifiableCollection(words);
only creates wrapper via which you can't modify words
, but it doesn't mean that words
can't be modified elsewhere. For example:
List<String> words = new ArrayList<>();
words.add("foo");
Collection<String> fixed = Collections.unmodifiableCollection(words);
System.out.println(fixed);
words.add("bar");
System.out.println(fixed);
result:
[foo]
[foo, bar]
If you want to preserve current state of words
in unmodifiable collection you will need to create your own copy of elements from passed collection and then wrap it with Collections.unmodifiableCollection(wordsCopy);
like if you only want to preserve order of words:
this.words = Collections.unmodifiableCollection(new ArrayList<>(words));
// separate list holding current words ---------^^^^^^^^^^^^^^^^^^^^^^