• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ArrayList sorting using Ccomparator

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
how to sort different types of objects
 
Saloon Keeper
Posts: 15450
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you
reply
    Bookmark Topic Watch Topic
  • New Topic