• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting objects in ArrayList

 
sindhu sheela
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you tried do you get any compilation error ? if yes what is the error message?
 
sindhu sheela
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Soumyajit Hazra
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sunny Bhandari
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
 
sindhu sheela
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All the answer where quite informative and cleared my doubt .thanks a lot once again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic