Create a compareTo to a Generic Class that Implements Comparable

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

    Would you like to introduce a requirement that K and J have a natural ordering that you can use? In this case you can declare your class DoubleKey like this:

    class DoubleKey, J extends Comparable>
    

    You can then define your DoubleKey's compareTo as you like. You can do things like:

    getFirstKey().compareTo(aThat.getFirstKey())
    

    You can't compare any instance of K to an instance of J, though. There is no ordering defined over those types.

    If these types don't necessarily have a natural ordering (many don't), you can take a Comparator and Comparator as parameters to the constructor of your DoubleKey. A class that does this already that you can use as an example is Google Guava's excellent Maps class (see specifically the newTreeMap methods and the bounds of the types they accept).

提交回复
热议问题