What is the equivalent of the C++ Pair in Java?

前端 未结 30 1508
一个人的身影
一个人的身影 2020-11-22 02:29

Is there a good reason why there is no Pair in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.<

30条回答
  •  Happy的楠姐
    2020-11-22 03:03

    Another way to implement Pair with.

    • Public immutable fields, i.e. simple data structure.
    • Comparable.
    • Simple hash and equals.
    • Simple factory so you don't have to provide the types. e.g. Pair.of("hello", 1);

      public class Pair implements Comparable> {
      
          public final FIRST first;
          public final SECOND second;
      
          private Pair(FIRST first, SECOND second) {
              this.first = first;
              this.second = second;
          }
      
          public static  Pair of(FIRST first,
                  SECOND second) {
              return new Pair(first, second);
          }
      
          @Override
          public int compareTo(Pair o) {
              int cmp = compare(first, o.first);
              return cmp == 0 ? compare(second, o.second) : cmp;
          }
      
          // todo move this to a helper class.
          private static int compare(Object o1, Object o2) {
              return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1
                      : ((Comparable) o1).compareTo(o2);
          }
      
          @Override
          public int hashCode() {
              return 31 * hashcode(first) + hashcode(second);
          }
      
          // todo move this to a helper class.
          private static int hashcode(Object o) {
              return o == null ? 0 : o.hashCode();
          }
      
          @Override
          public boolean equals(Object obj) {
              if (!(obj instanceof Pair))
                  return false;
              if (this == obj)
                  return true;
              return equal(first, ((Pair) obj).first)
                      && equal(second, ((Pair) obj).second);
          }
      
          // todo move this to a helper class.
          private boolean equal(Object o1, Object o2) {
              return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2));
          }
      
          @Override
          public String toString() {
              return "(" + first + ", " + second + ')';
          }
      }
      

提交回复
热议问题