I'm trying to understand what <K, V extends Comparable<? super V>>
actually means.
If compareTo()
is called to compare two Association<K,V>
objects; which of the two generic types K
or V
will be used to make the comparison?
What will happen when <K, V extends Comparable<? super K>>
is used instead?
public class Association<K, V extends Comparable<? super V>>
{
K key;
V value;
//---------------------------------------
public int compareTo(Association<K, V> object)
{
return this.key.compareTo(object.key);
}
}
edited the compareTo()
method.
First to explain your current definition:
public class Association<K, V extends Comparable<? super V>>
This means you are defining a public class called Association
This class has 2 type parameters: K
and V
. Of these, V
has the additional restraint that it must be comparable to ? super V
(= V
or a super type of V
).
Since you want ot compare by the key, it should be K
that is Comparable
. Additionally, you want to compare the Association
s themselves, so it too must be Comparable
.
So change your class definition to the following:
public class Association<K extends Comparable<K>, V> implements Comparable<Association<K, V>>
Your compareTo would then be:
public int compareTo(Association<K, V> other) {
return key.compareTo(other.key);
}