Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unordered pair in Java

I need a Java generic class to represent unordered pairs of any type. Meanwhile I see two solutions:

  • HashSet to store the pair elements
  • a Pair class with overriden hashCode and equals (to make Pair(a, b) and Pair(b, a) equal).

Does it make sense? What would you suggest?

like image 777
Michael Avatar asked Oct 22 '22 21:10

Michael


1 Answers

In your place I would roll out my own class. As long as you are interested in sets of only two objects, using HashMap, HashSet (which, incidentally, uses a HashMap internally anyway) or any other class designed for sets of arbitrary cardinality is a waste of resources and adds unneeded complexity.

Just create your own class with proper equals() and hashCode() implementations. Having a contains() operation, or even implementing parts of the Set interface, might also make sense.

One important note: make sure you document your class extensively - at least specify whether equals() performs an identity or an equality comparison for the contained objects, and what is the meaning of a null contained reference...

like image 160
thkala Avatar answered Nov 04 '22 22:11

thkala