aspose 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
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: 3649
    
  17

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