how to write write a set for unordered pair in Java

前端 未结 5 1780
夕颜
夕颜 2020-12-31 18:58

I need to have a Set (HashSet) such that if I insert a pair (a, b) and if (b, a) is already in the set, the insertion would just be ignored. How to

5条回答
  •  抹茶落季
    2020-12-31 19:13

    final class Pair {
      private final Set elements = new LinkedHashSet();
      Pair(T a, T b) {
        elements.add(a);
        if (!elements.add(b))
          throw new IllegalArgumentException();
      }
      @Override
      public int hashCode() {
        return elements.hashCode();
      }
      @Override
      public boolean equals(Object obj) {
        if (obj == this)
          return true;
        if (!(obj instanceof Pair))
          return false;
        return elements.equals(((Pair) obj).elements);
      }
    }
    

提交回复
热议问题