Image

Java Beginner

My first experience with java is to create a class that deals with coding a sorting class that will sort any object you give it without declaring it as an object within the "test" file. For the most part I'm just having issues getting it to work "with every comparable object". I know that every class is a subclass of Object so I assumed that by extending Object (which seems useless now that I think about it), it should be able to take any class and be able to sort it however, was not the case.
Another minor issue I was confused about was that if you create a global class to sort, shouldn't the compareTo be able to work only on the item you pass through it? By which you would not have to create a compareTo method within "global sort"?




import java.util.*; public class TestSort { public static void main(String[] args) { Manager[] managArr = new Manager[4]; managArr[0] = new Manager("Casey", 80000, 1988, 11, 28); managArr[0].setBonus(5000); managArr[1] = new Manager("Chuck", 45000, 1992, 03, 17); managArr[1].setBonus(1000); managArr[2] = new Manager("Greg", 55000, 1980, 06, 24); managArr[2].setBonus(3000); managArr[3] = new Manager("Sarah", 80000, 2000, 11, 01); managArr[3].setBonus(5000); Manager[] sortedManagArr = new Manager[managArr.length]; sortedManagArr = SortAnything.sort(managArr); } } //----------------------------------------------------------------------------- public class SortAnything extends Object { public static Object[] sort(Object[] toSort) { try{ for (int i = 0; i < (toSort.length - 1); i++) { boolean isSorted = true; for (int k = 1; k < (toSort.length - i); k++) { if (toSort[k].compareTo(toSort[k - 1])) { Object tempVar = toSort[k]; toSort[k] = toSort[k - 1]; toSort[k - 1] = tempVar; isSorted = false; } } if (isSorted) { break; } } return toSort; } //Exception class defined in another .java file catch(ObjectIsNotComparableException exp) { System.out.println("Object not comparable"); } finally { System.out.println("END"); } } } //----------------------------------------------------------------------------- import java.util.*; public class Manager extends Employee implements Comparable// { /** @param n the Manager's name @param s the salary @param year the hire year @param month the hire month @param day the hire day */ public Manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day); bonus = 0; } public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { if(b >= 0) { bonus = b; } else { b = 0; } } public int compareTo(Object otherObj) { Manager other = (Manager)otherObj; if(bonus < other.bonus) return -1; if(bonus > other.bonus) return 1; else return 0; } private double bonus; }



Thanks for the advice in advance.