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

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

    According to the nature of Java language, I suppose people do not actually require a Pair, an interface is usually what they need. Here is an example:

    interface Pair {
        public L getL();
        public R getR();
    }
    

    So, when people want to return two values they can do the following:

    ... //Calcuate the return value
    final Integer v1 = result1;
    final String v2 = result2;
    return new Pair(){
        Integer getL(){ return v1; }
        String getR(){ return v2; }
    }
    

    This is a pretty lightweight solution, and it answers the question "What is the semantic of a Pair?". The answer is, this is an interface build with two (may be different) types, and it has methods to return each of them. It is up to you to add further semantic to it. For example, if you are using Position and REALLY want to indicate it in you code, you can define PositionX and PositionY that contains Integer, to make up a Pair. If JSR 308 is available, you may also use Pair<@PositionX Integer, @PositionY Ingeger> to simplify that.

    EDIT: One thing I should indicate here is that the above definition explicitly relates the type parameter name and the method name. This is an answer to those argues that a Pair is lack of semantic information. Actually, the method getL means "give me the element that correspond to the type of type parameter L", which do means something.

    EDIT: Here is a simple utility class that can make life easier:

    class Pairs {
        static  Pair makePair(final L l, final R r){
            return new Pair(){
                public L getL() { return l; }
                public R getR() { return r; }   
            };
        }
    }
    

    usage:

    return Pairs.makePair(new Integer(100), "123");
    

提交回复
热议问题