Create a compareTo to a Generic Class that Implements Comparable

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

    You'll have to define a rule when a DoubleKey is smaller, bigger or equal to this one. That's what compare does. Maybe, that's my actual guess, it doesn't make much sense to compare to instances of DoubleKey.

    If you don't actual care how they're ordered and only need to implement any ordering, try this:

    public int compareTo(DoubleKey that){
        // real codes needs checks for null values!
        return (this.key1.toString() + this.key2.toString()).compareTo(that.key1.toString() + that.key2.toString());
    }
    

提交回复
热议问题