¿Se puede aplicar Collections.unmodified a Collections.EMPTY_MAP?

private final Map q;
public Info()
{
    this(Collections.EMPTY_MAP);
}

public Info(final Map q)
{
    this.qualifiers = new HashMap(q);
}

   public Map getQ()
{
    return Collections.unmodifiableMap(q);
}

Do I need to use Collections.unmodifiableMap() because I saw from the JAVA Docs of EMPTY_MAP that it is Immutable?

preguntado el 09 de marzo de 12 a las 15:03

If the Javadoc says it, then it's true. -

2 Respuestas

EMPTY_MAP is immutable but you still need to use Collections.unmodifiableMap(q) if Info has been instantiated with a map that is not EMPTY_MAP, using the second constructor...

respondido 09 mar '12, 15:03

No. You need to use Collections.unmodifiableMap() if you want to ensure that clients of your class never modify its internal representation - or rather, if you want to ensure that a failure will occur if a client ever tries to do so.

In the case where the internal map q is Collections.EMPTY_MAP then you wouldn't need to wrap it in a call to Collections.unmodifiableMap because it's already unmodifiable. However you have an alternative constructor that creates q as a modifiable Map, and in that case you'd need to protect it before returning it.

You can also simply return a copy of q in which case clients could modify the returned object without modifying your class's internal state nor raising an exception.

respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.