How to Sort Objects Using Collections.sort method
2 April 2007A programmer usually needs to sort a given set of inputs. Java has inbuilt set of API’s for sorting. There is a Comparable interface in java that needs to be implemented by class whose object needs to be compared. Java classes like “Integer”, “Date” implements this interface, so object of these classes can be sorted easily by Collection’s sort method. We can make a class that implements Comparable interface so that it’s objects can be sorted by “Collections.sort” method.
package test; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class ListExample { List list; public ListExample() { list = new ArrayList(); } private List getList() { return list; } public static void main ( String [] args ) { ListExample lExam = new ListExample(); List tempList = lExam.getList(); tempList.add(new Car(2)); tempList.add(new Car(3)); tempList.add(new Car(1)); tempList.add(new Car(6)); Collections.sort(tempList); Iterator iterator = lExam.getList().iterator(); while (iterator.hasNext()) { System.out.println(((Car)iterator.next()).getCapacity()); } } } package test;class Car implements Comparable{ int capacity;public Car(int c){ this.capacity=c; } public int compareTo(Object o) { int thisVal = this.capacity; int anotherVal = ((Car)o).capacity; return (thisVal<anotherval (thisval="=anotherVal"> </anotherval> } public int getCapacity(){ return capacity; } } Output : 1 2 3 6
Related Posts:
- Difference Between Comparable And Comparator Interface
- Rotating Elements In a List using Collections.rotate Method
- Defining custom tasks in ANT
- JSP implicit Session object (II)
- Using Arrays in Java
- Record Management System (III)
- Retrieving serialized objects from file
- Memory Leaks - I
- LinkedList (Generics)
- Factory Methods - I
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: How to Sort Objects Using Collections.sort method