Search code examples
javainheritancesubclasssuperclass

Sort a Superclass list of objects from two Subclasses


I have a List from the type Superclass A and in that List there are multiple objects from two Subclasses, Subclass B and Subclass C and want to sort them alphabetically and then filter the objects from either Subclass, something like this:

List <A> listA= new ArrayList<A>();

Collections.sort(listA);
    for (A iterator : listA)
        if (iterator instanceof B)
            System.out.println(iterator);

My question is how should I structure my code. Should I implement Comparable <A> and

public int compareTo(A a) {
    return name.compareTo(a.getName());
}

in both Superclass and Subclass? If I'm not being clear enough, please say so.

EDIT: I was getting an error due to a method I had left in one of the Subclasses that was already inherited from the Superclass, and I thought the error had anything to do with the structure of the Comparable<A>, because I wasn't certain if it was correct, but I already had the code as all you guys told me, but thanks anyway.


Solution

  • If you can compare instances of SuperclassA regardless of whether they are SubclassB or SubclassC, then your solution with the Comparable<SuperclassA> in the superclass alone makes perfect sense. If the implementation requires knowledge of data specific to the subclasses, add abstract methods that supply this data to SuperclassA, and call them in your comparator.