I need help with sorting an array that contains two different kind of classes that I have created. My two classes are "Human" that have a name and an age, then I have a class "Physicist" that inherits from human but also have the field "start year" when they started studying. Something like this:
public class Human implements Comparable<Human> {
private int age;
private String name;
public Human(int agein, String namein) {
age = agein;
name = namein;
}
public int compareTo(Human other) {
return Integer.compare(this.age, other.age);
}
}
public class Fysiker extends Human {
private int year;
public Fysiker(int startYear, int ageIn, String nameIn){
super(ageIn, nameIn);
}
public int compareTo(Fysiker other) {
if(other instanceof Fysiker && this.getAge() == other.getAge() ) {
return Integer.compare(this.year, other.year);
}
else {
return Integer.compare(this.getAge(), other.getAge());
}
}
}
What I want is that when I create an array mixed with humans and physicists and sort it, I want it to be sorted by age, and if two physicists are the same age, then they should get sorted by the year they have. For example like this:
Input:
name: Alex, age: 32, year: 2007
name: Nils, age: 30, year: 2008
name: Anders, age: 32, year: 2003
name: Erik, age: 18.
name: Olof, age: 31.
Sorted array:
name: Erik, age: 18.
name: Nils, age: 30, year: 2008
name: Olof, age: 31.
name: Anders, age: 32, year: 2003
name: Alex, age: 32, year: 2007
Are my compareTo methods wrong? Or why is it not working? I'm not getting any errors, the array just get sorted by age and then nothing more happens.
I'm thankful for your help!
Comparable, or could you also use an externalComparator?