So currently I\'m working on an assignment where I have to two classes, one is named Fysiker and the other Human. Fysiker is simply an extension of the Human class. Human has tw
In fact the method defined in the subclass :
public int compareTo(Fysiker o){
doesn't override the method in the base class :
public int compareTo(Human o){
You could define the subclass with the same signature to override effectively :
public int compareTo(Human o){
and using instanceof
to make the comparison according to the real type.
But it would be not a good idea either.
Indeed, Fysiker
would know how to compare Human
and Fysiker
but Human
would know how to compare only Human
s.
The Comparable.compareTo() contract states that :
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
Comparable
should not try to be interoperable between classes as it may violate the transitivity comparison principle.
I think that in your case, as alternative, you should use a Comparator
to sort elements.
You have two ways.
1) If the list contains only Fysiker
instances, declare a List
of Fysiker
and create a Comparator
:
List fysiker = new ArrayList();
...
Collections.sort(fysiker);
It limits the type of the elements that the List may accept but it is wished in this specific case.
2) If the list contains both Human
and Fysiker
instances, declare a List
of Human
and create a Comparator
:
List humans = new ArrayList();
...
Collections.sort(fysiker);
In the Comparator
implementation, you should check the type of the instances and compare them according to :
public class ComparatorHumanAndFysiker implements Comparator{
public int compare(Human o1, Human o2){
if (o1 instanceof Fysiker && o2 instanceof Fysiker){
Fysiker f1 = (Fysiker) o1;
Fysiker f2 = (Fysiker) o2;
// specific comparison
return ...;
}
// else mixed type comparison or human comparison
return o1.age - o2.age;
}
}