This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
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 Building Microservices this week in the Design 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: 4003
    
  18

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:


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
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
 
It's not a secret anymore!