To do so your Object should implements the comparable interface and provide the implementation of the method compareTo else you can implement the Comparator interface and provide the implementation of the method compare.
If you are using later then you should pass the comparator as argument to the method sort in the java.util.Arrays class.
e.g. Arrays.sort(your object array) if your object implements comparable interface.
Arrays.sort(object array,comparator) if your object implements Comparator interface.
SCJP 6,SCWCD 5,SCBCD 5
Failure is not an option.
Joined: Sep 11, 2007
I tried that, I don't understand "comparators" so I defaulted to "null" (natural order), and I received a casting exception. Code is in the "addApplication" method.
"Application" have no natural order. The "natural order" means the order you get by calling the Comparable.compareTo() method on the class, and Application doesn't implement Comparable; hence the ClassCastException.
If you want the Application objects to be sorted by the member "Software", which is what I think you've indicated, then you just need to add "implements Comparable<Application>" to your class declaration line, and add a compareTo method, like
This very common trick works because the String class implements Comparable already. The result of comparing two Applications is now the result of comparing their "software" members.
In your case java would have no idea how to sort your object?
based on software,version,serialno? No it has no idea how to sort user object unless you tell java how want to sort your object using Comparable interface.
lets say you want to sort your object nbased on serial version then the code would be like this.
compareTo return 0,1,-1 based on the comparison.
See the API for comparable interface.
Since String,Wrapper classes already implemented Comparable interface you can directly use them to sort but your own class does not implement the Comparable interface,so you have to tell java how do you want your object to be sorted out. in this case using version no.
hope it helps you.