5

我需要一个 Java泛型类来表示任何类型的无序对。同时我看到两个解决方案:

  • HashSet存储对元素
  • 一个Pair具有覆盖hashCodeequals(使Pair(a, b)Pair(b, a)相等)的类。

是否有意义?你有什么建议?

4

1 回答 1

3

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...

于 2012-12-22T10:08:18.563 回答