Generic pair class

后端 未结 14 1690
情话喂你
情话喂你 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:29

    My version of Pair. This also handles compares. PS : Most of the code is taken from AOSP.

    package util;
    
    import java.util.Objects;
    
    public class Pair, S extends Comparable>
      implements Comparable> {
    
        public final F first;
        public final S second;
    
        /**
         * Constructor for a Pair.
         *
         * @param first  the first object in the Pair
         * @param second the second object in the pair
         */
        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    
        /**
         * Checks the two objects for equality by delegating to their respective
         * {@link Object#equals(Object)} methods.
         *
         * @param o the {@link Pair} to which this one is to be checked for equality
         * @return true if the underlying objects of the Pair are both considered
         * equal
         */
        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Pair)) {
                return false;
            }
            Pair p = (Pair) o;
            return Objects.equals(p.first, first) && Objects.equals(p.second, second);
        }
    
        /**
         * Compute a hash code using the hash codes of the underlying objects
         *
         * @return a hashcode of the Pair
         */
        @Override
        public int hashCode() {
            return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
        }
    
        /**
         * Convenience method for creating an appropriately typed pair.
         *
         * @param a the first object in the Pair
         * @param b the second object in the pair
         * @return a Pair that is templatized with the types of a and b
         */
        public static , B extends Comparable> Pair create(A a, B b) {
            return new Pair<>(a, b);
        }
    
        @Override
        public int compareTo(Pair that) {
            int cmp = this.first.compareTo(that.first);
            if (cmp == 0)
                cmp = this.second.compareTo(that.second);
            return cmp;
        }
    }
    

提交回复
热议问题