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

前端 未结 30 1007
一个人的身影
一个人的身影 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条回答
  • 2020-11-22 02:52

    How about http://www.javatuples.org/index.html I have found it very useful.

    The javatuples offers you tuple classes from one to ten elements:

    Unit<A> (1 element)
    Pair<A,B> (2 elements)
    Triplet<A,B,C> (3 elements)
    Quartet<A,B,C,D> (4 elements)
    Quintet<A,B,C,D,E> (5 elements)
    Sextet<A,B,C,D,E,F> (6 elements)
    Septet<A,B,C,D,E,F,G> (7 elements)
    Octet<A,B,C,D,E,F,G,H> (8 elements)
    Ennead<A,B,C,D,E,F,G,H,I> (9 elements)
    Decade<A,B,C,D,E,F,G,H,I,J> (10 elements)
    
    0 讨论(0)
  • 2020-11-22 02:53

    If anyone wants a dead-simple and easy to use version I made my available at https://github.com/lfac-pt/Java-Pair. Also, improvements are very much welcome!

    0 讨论(0)
  • 2020-11-22 02:53

    com.sun.tools.javac.util.Pair is an simple implementation of a pair. It can be found in jdk1.7.0_51\lib\tools.jar.

    Other than the org.apache.commons.lang3.tuple.Pair, it's not just an interface.

    0 讨论(0)
  • 2020-11-22 02:54

    android provides Pairclass (http://developer.android.com/reference/android/util/Pair.html) , here the implementation:

    public class Pair<F, S> {
        public final F first;
        public final S second;
    
        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    
        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Pair)) {
                return false;
            }
            Pair<?, ?> p = (Pair<?, ?>) o;
            return Objects.equal(p.first, first) && Objects.equal(p.second, second);
        }
    
        @Override
        public int hashCode() {
            return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
        }
    
        public static <A, B> Pair <A, B> create(A a, B b) {
            return new Pair<A, B>(a, b);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:54

    You can use Google's AutoValue library - https://github.com/google/auto/tree/master/value.

    You create a very small abstract class and annotate it with @AutoValue and the annotation processor generates a concrete class for you that has a value semantic.

    0 讨论(0)
  • 2020-11-22 02:55

    JavaFX (which comes bundled with Java 8) has the Pair< A,B > class

    0 讨论(0)
提交回复
热议问题