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?
when you tried do you get any compilation error ? if yes what is the error message?
Joined: May 20, 2008
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.
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.
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.