Create a compareTo to a Generic Class that Implements Comparable

前端 未结 6 904
野趣味
野趣味 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:29

    First way: use hashCodes, like

     public int compareTo(DoubleKey aThat){
         getFirstKey().hashCode() + getSecondKey().hashCode() - aThat.getFirstKey().hashCode() +   aThat.getSecondKey().hashCode();
     }
    

    (you should think more about formula)

    Second way: add comparator to constructor

    public DoubleKey(K key1, J key2, Comparator cmp){
    

提交回复
热议问题