Search code examples
javadictionarycollectionsclonemutability

Returning copies or clones of collections to prevent mutability


I need to provide a getter method for the values of a HashMap, however I can not allow changes made to the returned Collection or it's elements which will then reflect in the original HashMap I am obtaining the value set from. I am currently doing it like so:

public Collection<T> getCollection() {
    Collection<T> collection = map.values();
    return collection;
}

Will this adequately achieve what I set out to do, or will changes to the returned Collection still reflect in my HashMap? The reason I ask is because I know any changes to a Collection returned my a Map's .values() method reflect in the original Map. Thanks!


Solution

  • If you want a view of the values you can use Collections.unmodifiableCollection

    public Collection<T> getCollection() {
     Collection<T> view = Collections.unmodifiableCollection(map.values());
     return view;
    }
    

    This would give you a view, ie: clients can't mutate it, but mutations are visible to them.