A Java collection of value pairs? (tuples?)

后端 未结 19 2604
名媛妹妹
名媛妹妹 2020-11-22 05:43

I like how Java has a Map where you can define the types of each entry in the map, for example .

What I\'m looking for is a type

19条回答
  •  不知归路
    2020-11-22 05:49

    The Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, off the top of my head:

    public class Pair {
    
      private final L left;
      private final R right;
    
      public Pair(L left, R right) {
        assert left != null;
        assert right != null;
    
        this.left = left;
        this.right = right;
      }
    
      public L getLeft() { return left; }
      public R getRight() { return right; }
    
      @Override
      public int hashCode() { return left.hashCode() ^ right.hashCode(); }
    
      @Override
      public boolean equals(Object o) {
        if (!(o instanceof Pair)) return false;
        Pair pairo = (Pair) o;
        return this.left.equals(pairo.getLeft()) &&
               this.right.equals(pairo.getRight());
      }
    
    }
    

    And yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.)

提交回复
热议问题