• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting in Java  RSS feed

 
Palash Jain
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to sort a vector which contains differnt objects, say ObjectA, B, C, D....

I want to sort them based on a known order say A, D, B, C.

Does Java has an API which does that or what is the best algoritm I can use in Java?

Thanks,
Palash
 
Chris Dempsey
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have your objects implement the java.lang.Comparable interface. Then you can use java.util.Collections.sort to sort the objects into their natural ordering.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Implementing Comparable defines a "natural sorting order" for the class that implements it. If the sorting order that you want is not in some clear way the preferred sorting order for the class, consider writing a class implementing the java.util.Comparator interface. This, too, will allow you to sort using Collections.sort(), TreeSet and so on.

- Peter
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
moving this to thie intermediate forum where I think its a bit more appropriate.
So please add your replies there. Thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!