Comparable and Comparator Interface in Java

前端 未结 3 1614
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 08:40

I want to write a generic Pair class, which has two members: key and value. The only requirement to this class is that both key and value should implements the Comparable in

3条回答
  •  萌比男神i
    2020-12-18 09:25

    I would declare my class as such:

    public class Pair, T2 extends Comparable> 
    

    Meaning that objects are comparable with objects of the same type as they are (your error means that the compiler cannot make sure objects are compared to other objects of the same type).


    Your code with my edits compiles properly:

    public class Pair, T2 extends Comparable> {
        private T1 key;
        private T2 value;
    
        public T1 getKey() {
            return key;
        }
    
        public T2 getValue() {
            return value;
        }
    
        public final Comparator> KEY_COMPARATOR = new Comparator>() {
            public int compare(Pair first, Pair second) {
                return first.getKey().compareTo(second.getKey());
            }
        };
    
        public static void test() {
            Pair p1 = new Pair();
            Pair p2 = new Pair();
    
            p1.KEY_COMPARATOR.compare(p1, p2);
        }
    }
    

    You should however make a separate class (or a static final class) of the comparator so that it is more intuitive to use & also does not increase the weight of each Pair instance.

提交回复
热议问题