I am currently working on an assignment and I am almost done except for one part.
I need to sort some of the objects in the array based on whether they are in Accounting or Information Systems. I setup the compareTo method but I do not believe I did it right or else I just don't know how to call on it as I did and it is not doing what I thought it would do.
This is driving me nuts as it is the last thing I have to do and I can't figure it out, any help would be great.
Here is the Comparable Inteface
public interface Comparable {
public abstract int compareTo(Employee c);
}//end comparable
Here is my code in the Department class:
public class Department implements Comparable {
public int compareTo(Employee e){
int compareAge = ((Employee) e).getAge();
return e.getAge() - compareAge;
}//end
}//end department
Here is my code for the main method:
public class Company {
public static void main(String [] args){
Employee[] e = new Employee[13];
PrimeAgeChecker p = new PrimeAgeChecker();
Department d = new Department();
e[0] = new Employee("Counting Guru",55,"Accounting");
e[1] = new Employee("Counting Pro",45,"Accounting");
e[2] = new Employee("Counting Savvy",40,"Accounting");
e[3] = new Employee("Counting Novice",25,"Accounting");
e[4] = new Employee("Sales Guru",50,"Marketing");
e[5] = new Employee("Sales Pro",48,"Marketing");
e[6] = new Employee("Sales Savvy",38,"Marketing");
e[7] = new Employee("Hiring Guru",58,"Human Resrouces");
e[8] = new Employee("Hiring Pro",47,"Human Resrouces");
e[9] = new Employee("Hacking Pro",47,"Information Systems");
e[10] = new Employee("Hacking Guru",51,"Information Systems");
e[11] = new Employee("Hacking Savvy",38,"Information Systems");
e[12] = new Employee("Hacking Novice",23,"Information Systems");
for(int i = 0;i<e.length;i++){
if(e[i].getDept().equals("Accounting") || e[i].getDept().equals("Information Systems")){
d.compareTo(e[i]);
System.out.println(e[i]);
}//end if
else{
System.out.println(e[i] + " " + p.isPrime(e[i]));
}
}//end
}//end main
}//end company
P.S. Sorting the ages of Employees code HAS to go into the Department Class as per the assignment instructions
publicandabstractare implied, no need to specify themComparableis an interface from thejava.langpackage. Defining your ownComparableclass is a very bad idea - it will only lead to confusion for anyone (including you) reading your code. Name it something else, or use thejava.lang.Comparableinterface instead.