How to Sort Objects Using Collections.sort method

2 April 2007

A 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

del.icio.us:How to Sort Objects Using Collections.sort method  digg:How to Sort Objects Using Collections.sort method  spurl:How to Sort Objects Using Collections.sort method  wists:How to Sort Objects Using Collections.sort method  simpy:How to Sort Objects Using Collections.sort method  newsvine:How to Sort Objects Using Collections.sort method  blinklist:How to Sort Objects Using Collections.sort method  furl:How to Sort Objects Using Collections.sort method  reddit:How to Sort Objects Using Collections.sort method  fark:How to Sort Objects Using Collections.sort method  blogmarks:How to Sort Objects Using Collections.sort method  Y!:How to Sort Objects Using Collections.sort method  smarking:How to Sort Objects Using Collections.sort method  magnolia:How to Sort Objects Using Collections.sort method  segnalo:How to Sort Objects Using Collections.sort method  gifttagging:How to Sort Objects Using Collections.sort method

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

Leave a Reply