0

I have a HashMap[CustomEnumeration, String] as a member of my class.

But if i give a getter to it, external objects will be able to modify it (adding new couples of entry/value or removing some of them). And I don't want that.

So I gave a look at the methods entrySet() of Map, but they say that modifications from one of both objects (the returned set and the original map) are backed on the other side.

So what is the best way of dealing with this ? Is there a way to get an immutable set/map from my map ?

P.S I have looked at How to get a immutable collection from java HashMap?, but I am sure I don't need such complexity, as I only use a "nearly primitve type" and I primitive type. So, what is the best solution in my case ?

Community
  • 1
  • 1
loloof64
  • 5,252
  • 12
  • 41
  • 78

2 Answers2

2

Do you mean

public Map<K, V> getMap() {
    return Collections.unmodifiableMap(map);
}

This returns a wrapper for you map which is unmodifiable. Note: the object in the map could still be modified.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Do you mean that I can't add/remove couple of entry/value, but that the already existing objects can be modified ? If so, it does not matter :) All I need is the fact that no more couple of associations are added, nor no one removed :) – loloof64 Dec 20 '13 at 10:57
  • 1
    @LaurentBERNABE Nothing can be added, replaced i.e. put(key, value), or removed, either directly or by using keySet(), entrySet() values() or iterator(). Note: if you change the underlying map, those changes are visible. – Peter Lawrey Dec 20 '13 at 11:05
  • 1
    I wish the official Java documentation made these points more visible ... collections are so critical and importants – loloof64 Dec 20 '13 at 11:07
1

See

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
return new UnmodifiableMap<K,V>(m);
}

method of Collections class.

Java Doc

/**
 * Returns an unmodifiable view of the specified map.  This method
 * allows modules to provide users with "read-only" access to internal
 * maps.  Query operations on the returned map "read through"
 * to the specified map, and attempts to modify the returned
 * map, whether direct or via its collection views, result in an
 * <tt>UnsupportedOperationException</tt>.<p>
 *
 * The returned map will be serializable if the specified map
 * is serializable.
 *
 * @param  m the map for which an unmodifiable view is to be returned.
 * @return an unmodifiable view of the specified map.
 */
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Thank you, once I read Excellent Bruce Eckel tutorial, and he pointed to this solution ... but I forgot it :(. Anyway thanks. Also, what can be modified : all values ? all keys ? or nothing at all ? – loloof64 Dec 20 '13 at 11:00
  • 1
    You cannot modify this collection. So nothing no keys no values. – Aniket Thakur Dec 20 '13 at 11:02