commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Neil O'Toole <neiloto...@users.sourceforge.net>
Subject [collections] Map.Entry and KeyValue
Date Mon, 22 Sep 2003 04:22:06 GMT
> > ** I had a swift look through [collections] and [lang], and didn't
> see
> > a simple KeyValuePair implementation... Have I missed this
> somewhere?
> 
> DefaultMapEntry IIRC is the simple Map.Entry impl.
> Stephen
>

Although one (including my good self!) might initially think that a
key-value class and a Map.Entry class are interchangeable, this is not
in fact the case. DefaultMapEntry is not suitable for use as a general
purpose KeyValue class, as it is effectively non-extendable (and there
are many cases where it is useful to extend a KeyValue class). In fact,
DefaultMapEntry (or at the very least its #equals and #hashcode
methods) should be declared final so that users won't make the mistake
of subclassing it.

DefaultMapEntry is not extendable because the #equals method is
contractually specified by Map.Entry to only evalute the members of
Map.Entry. A non-trivial subclass of DefaultMapEntry will add members
that will be used in #equals comparision. To make use of these members
in #equals will of course violate the Map.Entry#equals contract.

This non-extensibility property applies to any class that inherits or
implements an #equals method with a similar closed #equals contract,
and any such class should be declared final to prevent accidental
subclassing (or again, at the very least the #hashcode and #equals
methods should be declared final, though the user might just ignore
those methods, resulting in unfortunate code).

My suggested solution is to add a class "KeyValue.java" containing the
code from DefaultMapEntry, but not implementing Map.Entry.
DefaultMapEntry can then subclass KeyValue and implement Map.Entry, and
be declared final. 

- Neil



Mime
View raw message