• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to sort different type of Objects in the list  RSS feed

 
Micheal John
Ranch Hand
Posts: 344
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am having a list. This list contains the following objects.
1. Customer
2. Employee
3. Driver

In the list collection, the above all objects will be there.

For example: If I am printing the list:

list value:: [com.ex.Customer123,com.ex.Employee233,com.ex.Driver44,com.ex.Driver43,com.ex.Employee333]

I want to sort thr list, so that all the customer object should come forts, then all the employee objects and then Driver objects..

How to achieve this?any idea..or sample coding will be useful

Note: I know, I can use Iterator, and iterate it and check the instanceof ... but I want to know any built-in function available in java..either in Collections package..or some other else..

I knoe using sort of Collections package, we can send the list as argument and one of the attribute from the object to sort it out. But my case is different I think..
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you heard of java.util.Comparator? It is an interface you can implement that lets you define comparison logic. Once you've got one of them Collections.sort(List list, Comparator comparator) will do the sorting for you.
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul is right. Here's an excellent OnJava article on making objects Comparable vs. creating a Comparator.

http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html

The article discusses the pros and cons of each approach and gives a good example of when you would employ each one.

In your case, you probably want to make a Comparator for whatever base class Customer, Employee, and Driver extend. Then you can use instanceof inside the compare() method to make sure Customers > Employees > Drivers.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!