Search code examples
javaarraylistcollectionscomparatorcomparable

impose order (not sorting) using comparator on a wrapper class of a list in Java


I have a class, person. it has Age, Name, Height, etc. I am creating a class called PersonCollection which is a wrapper of a list (an ArrayList).

I will like to be able to compare Person objects using the PersonCollection class, Which means, I don't want to make the Person class implement the Comparable interface, I would like the PersonCollection to implement the Comparator interface.

I have having trouble doing that. I have implemented the compare method but still when I compare Person Objects it doesn't work.

for example this code gives me an error (people is an ArrayList

public void insert (Person p){
    for(int i = 0; i < people.size(); i++){
        if (people.get(i) > p){
            //Do something
        }
    }
} 

I know how to use Comparator for sorting, this is different. I am fully aware of other possible and maybe better solutions (any priority queue class or some sort of sortedset classes)

I wish to do that for ArrayList for a specific reason and I kindly ask you to base your solutions on this instead of suggest other Data structures.


Solution

  • You can write a custom Comparator and use the compare(a, b) method.

    https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-

    Your code would look like

    if (myComparator.compare(people.get(i), p) > 0 ) {