| Author |
Sorting objects in ArrayList
|
sindhu sheela
Greenhorn
Joined: May 20, 2008
Posts: 26
|
|
Hi All,
I just wanted to know on what basis are objects in ArrayList get Sorted when i sort an ArrayList using Collections.sort(arraylist);
this sort method internally uses Arrays.sort(array).But still on what basis are the objects sorted?
Thanks in advance.
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
|
when you tried do you get any compilation error ? if yes what is the error message?
|
 |
sindhu sheela
Greenhorn
Joined: May 20, 2008
Posts: 26
|
|
|
no i did not get any compilation error.it was for my understanding and further implementation i wanted it.on what basis are the objects sorted. like i will attributes in the object as id,name,address etc.
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14685
|
|
Collections.sort uses the Comparable interface to sort the object in the list, so these objects must implement Comparable and implement its method. The only method of that interface is int compareTo(T o). That is where you decide which fields of your objects have to be compared.
Or, a Comparator can be used to compare the objects. In this case, Collections.sort(List<T> list, Comparator<? super T>) has to be used.
|
[My Blog]
All roads lead to JavaRanch
|
 |
Soumyajit Hazra
Ranch Hand
Joined: Jun 26, 2007
Posts: 136
|
|
i wanted it.on what basis are the objects sorted. like i will attributes in the object as id,name,address etc.
Looking at your requirement either you can take id or name as a basis of sorting. Suppose you have some Student objects and you want to show list of students in ascending order of id/roll or you can present the list in alphabetical order in case of name. Check the java doc that how Collection.sort works and take a detailed study of Comparable and Comparator interfaces.
|
Java Programmer | SCJP 1.5 | SCWCD 1.4
|
 |
Sunny Bhandari
Ranch Hand
Joined: Dec 06, 2010
Posts: 446
|
|
I have posted a bog entry for your answer:
http://extreme-java.blogspot.com/2011/01/how-to-sort-arraylist-using-collections.html
|
 |
sindhu sheela
Greenhorn
Joined: May 20, 2008
Posts: 26
|
|
|
All the answer where quite informative and cleared my doubt .thanks a lot once again.
|
 |
 |
|
|
subject: Sorting objects in ArrayList
|
|
|