The moose likes Java in General and the fly likes Sorting two Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting two Classes" Watch "Sorting two Classes" New topic

Sorting two Classes

hans meiser

Joined: Aug 15, 2001
Posts: 1
i have the problem, that i want to merge two lists of different classes to one list and then i want to sort this list.
After sorting i have to know which class the elements belong to and use different methods for each element.
If i merge two lists, how can i get out the types (classes) of the objects. A ArrayList just returns Objects. How can i cast them to the original class.
Anyone any idea?? Or some code to look how to do?
Thanks in regard
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

1) have them both implement an interface
2) use either object.getClass() or instanceOf
3) use reflection to choose and execute the required code
I usually go for the Interface solution, gather the common functionality into an interface of common operations (they can both be compared for sorting and they can be executed) then sort and execute a bunch of interfaces rather than object instances.
I agree. Here's the link:
subject: Sorting two Classes
It's not a secret anymore!