Suppose I have two classes CLassA and CLassB. And they have one atributte in common, for example the number of elements that each class holds.
How can i create a collection from objects of ClassA and CLassB and sort by that attribute (ascending of descending order, doesn't matter)?
I made a collection of type but when I try to implement the Comparable Interface i can't acess to that method (a get that returns the nr of elements for example).
What solutions do I have?
Thanks for your help!
You could make a custom java.util.Comparator and sort using the Collections.sort(List list, Comparator c) method.
If you have access to the declaration of CLassA and ~B, then go with a common interface, if not you could write a Wrapper for both Classes:
I defined - against the description - my own classes ~A and ~B, to have something to test. Imagine they're foreign source, and you just have access to the classes.
Hmm.. is it possible for ClassA and ClassB to share an interface?
Then just sort the list like so:
Really ClassA and ClassB should be related either through an inheritance hierarchy, or by a common interface if you are going to put them both in the same collection.
The simplest thing would be to have a common interface that provides an accessor method for the common attribute. And then the comparator could use that method (through the interface) for fetching the value from ClassA's instance as well as ClassB's instance.