MakeItPossible
MakeItPossible

Reputation: 23

how can a subclass use the superclass's comparator?

There is a comparator in the super class named 'comparator'. In the subclass, I would like to compare two objects of it, how can I use the super class's comparator to compare them?

This statement is in the super class(it has been initialized in the constructor of the subclass):

    final Comparator<Node> comparator;

This function is in the subclass:

 /**
 * judge wheter pq[i] is less than pq[j]
 * @param i
 * @param j
 * @return true if pq[i] is less than pq[j]
 */
private boolean less(int i, int j) {

}

I would like to compare pq[i] and pq[j] in the function named 'less' using the comparator, so how can I do it?

Upvotes: 0

Views: 710

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

I do not see a problem with using a Comparator, defined on the superclass, for the subclass. Given below is a simple demo (Note: not following best practices).

Demo:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class A {
    int x;

    @Override
    public String toString() {
        return "x=" + x;
    }
}

class B extends A {

}

public class Main {
    public static void main(String[] args) {
        Comparator<A> comp = (a1, a2) -> Integer.compare(a1.x, a2.x);
        
        B b1 = new B(); b1.x = 10;
        B b2 = new B(); b2.x = 5;
        B b3 = new B(); b3.x = 15;
        List<B> list = new ArrayList<>(List.of(b1, b2, b3));
        
        list.sort(comp);
        System.out.println(list);
    }
}

Output:

[x=5, x=10, x=15]

Update:

Thanks to Holger

You can replace Comparator<A> comp = (a1, a2) -> Integer.compare(a1.x, a2.x) with Comparator<A> comp = Comparator.comparingInt(a -> a.x).

Upvotes: 3

OLezhko
OLezhko

Reputation: 150

You can simply use Comparator's compare method which returns a positive number when the first object is more, 0 when objects are equal, and a negative when the first object is less than the second one.


    /**
     * judge wheter pq[i] is less than pq[j]
     * @param i
     * @param j
     * @return true if pq[i] is less than pq[j]
     */
    private boolean less(int i, int j) {
        return comparator.compare(pq[i], pq[j]) < 0;
    }

Upvotes: 0

Related Questions