File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ArrayList sorting using Ccomparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "ArrayList sorting using Ccomparator" Watch "ArrayList sorting using Ccomparator" New topic
Author

ArrayList sorting using Ccomparator

rakeshdec kumar
Greenhorn

Joined: Feb 17, 2011
Posts: 9

ArrayList al=new ArrayList();

al.add("ram");
al.add("xyz");
al.add(11);
al.add(55);
al.add("25");


How to implement Comparator for this list to sort elements
Ravishanker kumar
Ranch Hand

Joined: Jul 20, 2006
Posts: 53
Here you are using different type of objects(String,Integer) into list.
Please use generic for collection.In this particular case,you can use natural order for string as below,

List al=new ArrayList();
al.add("ram");
al.add("xyz");
al.add("11");
al.add("55");
al.add("25");
System.out.println("Before sorting:"+al);
Collections.sort(al);
System.out.println("After Sorting:"+al);
rakeshdec kumar
Greenhorn

Joined: Feb 17, 2011
Posts: 9
how to sort different types of objects
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3370
    
    9
You first need to decide how two different objects compare, before you can sort them. How do 11 and "abc" compare, for instance?

If you want lexicographical sorting, you can do something like this:
rakeshdec kumar
Greenhorn

Joined: Feb 17, 2011
Posts: 9
thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ArrayList sorting using Ccomparator
 
Similar Threads
items are not displayed in c:forEach
List contents - number of occurrences ?
How do you avoid an ArrayList object from being modified, i.e. avoid adding and deleting its content
sending a Collection from JSP to Servlet
readonly ArrayList