Frank has posted 1 posts at DZone. View Full User Profile

HE-Collections - Java Collections independent from hashCode and equals

04.16.2012
| 1274 views |
  • submit to reddit

HE-Collection

Independence from hashCode() and equals(Object)

 

Motivation

Did you ever see a project where classes break the contract betweenthe methods hashCode() and equals(Object) defined injava.lang.Object? This contract says, that equal objects must provide the same hash-code. The criteria can be changed in any custom class by overriding the default implementations in java.lang.Object.

Legacy Projects may need "standard" Corrections

Objectsbreaking the contract can not be used in a Java-Standard-Collection (package java.util), because the collection will behave unpredictably.You may find this problem in a legacy project, where you are unable (because of risks or workload) to change any implementation of the hashCode() and equals(Object) methods.

Special Use Case may need "special" corrections

Another problem with the contract and Java-Standard-Collections can occur if you need - in a specal use case for example - other criteria for equality than implemented. In such a case, you would need to extend or wrap the values, so that the Java-Standard-Collection will use your use case specific implementations of hashCode() and equals(Object).

HE-Collection

"HE-Collection" is a new project on sourceforge. It's based on the Java-Standard-Collection and provides a kind of transparent wrapping- and switch-mechanism in order to achieve the independence mentioned above: Values that are stored in a HE-Collection don't need to implement the contract correctly. Calls to hashCode() and equals() from the Java-Standard-Collection to the value will be delegated to any other method.

The project HE-Collection can be found here.

0
Published at DZone with permission of its author, Frank Lemke.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)