View RSS Feed

My Java Tips

How to Sort Objects Using Collections.sort method

Rate this Entry
by , 11-08-2011 at 06:19 PM (4230 Views)
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.




Java Code:
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
		
	}

	public int getCapacity(){

		return capacity;

	}

}
Output :

1

2

3

6

Submit "How to Sort Objects Using Collections.sort method" to Facebook Submit "How to Sort Objects Using Collections.sort method" to Digg Submit "How to Sort Objects Using Collections.sort method" to del.icio.us Submit "How to Sort Objects Using Collections.sort method" to StumbleUpon Submit "How to Sort Objects Using Collections.sort method" to Google

Comments