• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList sorting using Ccomparator

 
rakeshdec kumar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to sort different types of objects
 
Stephan van Hulst
Bartender
Posts: 5334
48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic