简体   繁体   English

java中比较器中super的使用

[英]Use of super in Comparator in java

I understand in我明白在

Comparator < ? super T> comp

it returns the maximum element of the given collection, according to the order defined by the specified comparator.它根据指定比较器定义的顺序返回给定集合的最大元素。 But I don't understand the purpose of the但我不明白的目的

super T超级T

Could anyone possibly explain?谁能解释一下?

I understand in我了解

Comparator < ? super T> comp

it returns the maximum element of the given collection, according to the order defined by the specified comparator.它根据指定比较器定义的顺序返回给定集合的最大元素。 But I don't understand the purpose of the但是我不明白

super T超级T

Could anyone possibly explain?有人可以解释吗?

I understand in我了解

Comparator < ? super T> comp

it returns the maximum element of the given collection, according to the order defined by the specified comparator.它根据指定比较器定义的顺序返回给定集合的最大元素。 But I don't understand the purpose of the但是我不明白

super T超级T

Could anyone possibly explain?有人可以解释吗?

Lets take an example举个例子

interface Fruit {
    int getPrice();
}

class Orange implements Fruit {
    int price;

    public Orange(int price) {
        this.price = price;
    }

    @Override
    public int getPrice() {
        return price;
    }
}

interface Apple extends Fruit {
    int getAppleQuality();
}

class WineSapApple implements Apple {

    public int price, quality;
    public WineSapApple(int price, int quality) {
        this.price = price;
        this.quality = quality;
    }
    @Override
    public int getPrice() {
        return price;
    }
    @Override
    public int getAppleQuality() {
        return quality;
    }
}

class AppleQualityComparator implements Comparator<Apple> {
    public int compare(Apple a1, Apple a2) {
        return Integer.compare(a1.getAppleQuality(), a2.getAppleQuality());
    }
}

class FruitPriceComparator implements Comparator<Fruit> {
    public int compare(Fruit f1, Fruit f2) {
        return Integer.compare(f1.getPrice(), f2.getPrice());
    }
}

Okay now现在好了

        List<Fruit> fruits = List.of(new WineSapApple(100, 50), new Orange(10));
        Collections.sort(fruits, new FruitPriceComparator());
//        Collections.sort(fruits, new AppleQualityComparator()); compilation error

Importantly we want to re use the Comparator declared at super class level重要的是,我们要重新使用在超级 class 级别声明的比较器

    List<Apple> apples = List.of(new WineSapApple(100, 50), new WineSapApple(150, 75));
    Collections.sort(apples, new FruitPriceComparator()); //<--- reason for `? super T`
    Collections.sort(apples, new AppleQualityComparator());

I understand in我了解

Comparator < ? super T> comp

it returns the maximum element of the given collection, according to the order defined by the specified comparator.它根据指定比较器定义的顺序返回给定集合的最大元素。 But I don't understand the purpose of the但是我不明白

super T超级T

Could anyone possibly explain?有人可以解释吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM