I have 2 classes: person and employee and an interface Human Within my Person class, I have a compareTo Method (Human h) Which assigns the +1,-1 and 0 for the person's age. My class employee = public class Employee extends Person implements Human = I have a compareTo method as well, which needs to account for the employees salary if the age is the same (for sorting).
I am not quite sure how to tackle this? I was able to make the compreTo for the Persons class but I am not sure how to have both person and employe sorted here.
Thank you for the help.
I have already tried this in my Employee class:
compareTo (Human h) {
Employee e = (Employee)h;
if (super.compareTo(h) == 0 && getSalary ()< e.getSalary())
return -1;
else if (super.compareTo(h) == 0 && getSalary () == e.getSalary())
return 0;
else
return 1;
}
This one works, but I want to be able to use instanceof to solve this problem:
public int compareTo(Human h) {
// TODO Auto-generated method stub
if (getAge() < h.getAge()) {
return -1;
} else if (getAge() > h.getAge()) {
return 1;
} else {
Employee e = (Employee)h;
// age is identical: compare salary
if (getSalary() < e.getSalary()) {
return -1;
} else if (getSalary() > e.getSalary()) {
return 1;
} else {
return 0;
}
}
}
Below I had proved the amount of code I think is necessary for this question:
public interface Human extends Comparable <Human>{
//extends = is a
int getAge();
String getName();
}
public class Person implements Human {
private int age;
private String name;
public int compareTo(Human h) {
//System.out.println(this.age + ". " +h.getAge());
if (h.getAge() > getAge())
return -1;
else if (getAge() == h.getAge())
return 0;
else
return 1;
}
public class Employee extends Person implements Human{
private int salary;
private String employer;
public int compareTo(Human h) {
???
}
public static void main(String[] args) {
ArrayList<Human> p = new ArrayList<Human>();
p.add(new Person("A", 1));
p.add(new Employee("B", 31, "E1", 45000));
p.add(new Person("C", 122));
p.add(new Employee("D", 3, "E2", 54321));
p.add(new Person("E", 21));
p.add(new Employee("F", 31, "E1", 21000));
p.add(new Employee("G", 31, "E1", 38000));
System.out.println(p);
Collections.sort(p);
System.out.println(p); }
This is what I am trying to test:
non sorted: [Person:[A, 1], Employee:[B, 31][E1, 45000], Person:[C, 122], Employee:[D, 3][E2, 54321], Person:[E, 21], Employee:[F, 31][E1, 21000], Employee:[G, 31][E1, 38000]]
sorted: [Person:[A, 1], Employee:[D, 3][E2, 54321], Person:[E, 21], Employee:[F, 31][E1, 21000], Employee:[G, 31][E1, 38000], Employee:[B, 31][E1, 45000], Person:[C, 122]]
Any help would be appreciated.