Generic pair class

后端 未结 14 1684
情话喂你
情话喂你 2020-12-01 16:49

Just attempting this question I found in a past exam paper so that I can prepare for an upcoming Java examination.

Provide a generic class Pair for representing pair

14条回答
  •  爱一瞬间的悲伤
    2020-12-01 17:15

    The need for a Pair class usually crops up in larger projects - I'm about to (re)implement one for the current project (as previous implementations are not accessible).

    Generally I make it an immutable POJO, with a convenience function to create instances. For example:

    public class Pair
    {
        public final T first;
        public final U second;
        public static  Pair of(T first, U second);
    }
    

    So that the end-user can write:

    return Pair.of (a, b);
    

    and

    Pair p = someThing ();
    doSomething (p.first);
    doSomethingElse (p.second);
    

    As mentioned above, the Pair class should also implement hashCode(), equals(), optional-but-useful toString(), as possibly clone() and compareTo() for use where these are supported by T and U - though extra work is required to describe how these contracts are supported by the Pair class.

提交回复
热议问题