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

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

    HashMap compatible Pair class:

    public class Pair {
        private A first;
        private B second;
    
        public Pair(A first, B second) {
            super();
            this.first = first;
            this.second = second;
        }
    
        public int hashCode() {
            int hashFirst = first != null ? first.hashCode() : 0;
            int hashSecond = second != null ? second.hashCode() : 0;
    
            return (hashFirst + hashSecond) * hashSecond + hashFirst;
        }
    
        public boolean equals(Object other) {
            if (other instanceof Pair) {
                Pair otherPair = (Pair) other;
                return 
                ((  this.first == otherPair.first ||
                    ( this.first != null && otherPair.first != null &&
                      this.first.equals(otherPair.first))) &&
                 (  this.second == otherPair.second ||
                    ( this.second != null && otherPair.second != null &&
                      this.second.equals(otherPair.second))) );
            }
    
            return false;
        }
    
        public String toString()
        { 
               return "(" + first + ", " + second + ")"; 
        }
    
        public A getFirst() {
            return first;
        }
    
        public void setFirst(A first) {
            this.first = first;
        }
    
        public B getSecond() {
            return second;
        }
    
        public void setSecond(B second) {
            this.second = second;
        }
    }
    

提交回复
热议问题