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

前端 未结 30 1076
一个人的身影
一个人的身影 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:54

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

    public class Pair {
        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  Pair  create(A a, B b) {
            return new Pair(a, b);
        }
    }
    

提交回复
热议问题