Create a compareTo to a Generic Class that Implements Comparable

前端 未结 6 907
野趣味
野趣味 2020-12-31 01:29

I have a Generic Class with two type variables, which implements java.lang.Comparable.

public class DoubleKey implements Comparable

        
6条回答
  •  清歌不尽
    2020-12-31 01:34

    so to summarize the said above and to puzzle it together into a working code this is:

        public class DoubleKey, J extends Comparable>
            implements Comparable> {
    
        private K key1;
        private J key2;
    
        public DoubleKey(K key1, J key2) {
            this.key1 = key1;
            this.key2 = key2;
        }
    
        public K getFirstKey() {
            return this.key1;
        }
    
        public J getSecondKey() {
            return this.key2;
        }
    
        public int compareTo(DoubleKey that) {
    
            int cmp = this.getFirstKey().compareTo(that.getFirstKey());
            if (cmp == 0)
                cmp = this.getSecondKey().compareTo(that.getSecondKey());
            return cmp;
        }
    }
    

提交回复
热议问题