| Author |
Sorting with Treeset
|
RaviSingh Kumar
Ranch Hand
Joined: Sep 04, 2007
Posts: 52
|
|
Hi,
I have an employee object having fields as employee first name,last name, employee Id , salary, designation .
I have to store it in treeset. But when i want to retrive it , it must be sorted according to employee id.
The problem is that i am unable to sort it according to employee id.(But able to sort according to first name, last name etc using comparable interface).
Please let me now how to do it.
Thanks in advance
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
|
to sort an object use Comparator or Comparable interfaces .to know more search in google
|
 |
RaviSingh Kumar
Ranch Hand
Joined: Sep 04, 2007
Posts: 52
|
|
I have used the comparable interface. But when i implement the compareTo method i am unable to sort on the basis of employee id since it is integer.
But i am able to sort on the basis of first name, last name etc.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
|
|
Why have you used Comparable? Its documentation says it implies a "natural ordering" which you don't have for employees. You have several possible orderings, eg by name, seniority, salary, ID number, all of which might be valid. Not one "natural" ordering.
So you want to pass a Comparator<Employee> which simply works out the difference between the ID numbers. If they are ordinary positive ints you can simply subtract the IDs to get a result.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Campbell Ritchie wrote:If they are ordinary positive ints you can simply subtract the IDs to get a result.
And if they are not the following works always:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Brijesh Verma
Greenhorn
Joined: Apr 20, 2009
Posts: 16
|
|
do one thing put all Employee object in list object and
call this methos Collections.sort(listObject); in that class where you want sorting
put this in Employee class
public int compareTo(Object o) {
Employee e = (Employee ) o;
return this.id.compareToIgnoreCase(e.getId());
}
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
|
|
|
If the id field is an int, that last code will fail to compile. As I said: not Comparable<Employee> but one or more Comparator<Employee> objects.
|
 |
 |
|
|
subject: Sorting with Treeset
|
|
|