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

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

    public class Pair {
    
        private final K element0;
        private final V element1;
    
        public static  Pair createPair(K key, V value) {
            return new Pair(key, value);
        }
    
        public Pair(K element0, V element1) {
            this.element0 = element0;
            this.element1 = element1;
        }
    
        public K getElement0() {
            return element0;
        }
    
        public V getElement1() {
            return element1;
        }
    
    }
    

    usage :

    Pair pair = Pair.createPair(1, "test");
    pair.getElement0();
    pair.getElement1();
    

    Immutable, only a pair !

提交回复
热议问题