Hi Everyone,
I am searching the most effective way of sorting a list of objects.

Say i have a bean

public class MyClass {
	private string name;
	private string id;
	
	// Getters and setters
}

Now say we put some values in a List

List<MyClass> myClassList  = new ArrayList<MyClass>();


MyClass myClass = new MyClass();

//In some iterator adding items to the list
myClass.setName("John");
myClass.setId("100");

myClassList.add(myClass);

myClass.setName("Arnold");
myClass.setId("101");


myClassList.add(myClass);


// Say now my list has two entries of myClass object.

Now how do i sort myClassList based on Name.

Implement the Comparable interface.
http://onjava.com/pub/a/onjava/2003/03/12/java_comp.html
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html

Then use the Collections.sort(yourArrayList) method
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List%29

In fact the first link shows the whole process. If you are good at reading method documentation all you need to do is look at the second link, implement that interface (it only has one method), then call Collections.sort(yourArrayList). Otherwise just read the first link and follow directions.

commented: Nice resource +4

Awesome. Indeed the first link is a good resource for anyone trying to learn sorting.Thanks a lot BestJewSinceJC

But i have a little problem. I wont be able to modify my bean "MyClass" as it will be an existing object from the product i am using. So any other idea?

Make a class that extends the MyClass, then implement the Comparable interface on that class instead. Basically do the exact same thing, except you'll have to extend MyClass as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.