问题< T extends Comparable&lt ;?超级T> [英] Problem with <T extends Comparable<? super T>>

查看:369
本文介绍了问题< T extends Comparable&lt ;?超级T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个类:1.class 算法 max()集合

I have a three class: 1.class Algorithm having max() finding maximum value in a Collection:

public class Algorithm {

    public static <T extends Comparable<T>> T max(Collection<? extends T> coll) {
        T max = coll.iterator().next();

        for (T elm : coll) {
            if (max.compareTo(elm) < 0)
                max = elm;
        }

        return max;
    }
}

2.Class / code>:

2.Class Fruit:

public class Fruit implements Comparable<Fruit> {
    private String name;
    private int size;

    public Fruit(String name, int size) {
        this.name = name;
        this.size = size;
    }

    public int compareTo(Fruit that) {
        if (size < that.size)
            return -1;
        else if (size == that.size)
            return 0;
        else
            return 1;
    }
}

3.class Apple extends 水果

3.class Apple extending Fruit:

public class Apple extends Fruit {
    public Apple(int size) {
        super("Apple", size);
    }
}

现在的问题是:

public class Main
{
    public static void main(String[] args) {        
        Apple a1 = new Apple(10);
        Apple a2 = new Apple(34);

        List<Apple> apples = Arrays.<Apple>asList(a1, a2);

        System.out.println(Collections.max(apples).size);
    }
}

根据此帖 Java - 语法问题:什么是我应该这样写: public static< T extends Comparable<超级T> T max(Collection< ;? extends T> coll)。但它现在工作正常。为什么? 未实现可比较的< Apple> ,并且没有 super

According to this post Java - Syntax Question: What is I should wrote it this way: public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll). But it is working fine now.Why? Class Apple does not implement Comparable<Apple> and there is no super.

[UPDATE]

Java泛型与集合本书说:

[UPDATE]
Java Generics and Collections Book says:

没有超级通配符,找到最大值 List< Apple>
将是非法的,即使发现 List< Fruit> 的最大值是允许的

Without the super wildcard, finding the maximum of a List<Apple> would be illegal, even though finding the maximum of a List<Fruit> is permitted.


推荐答案

使用 Collections.max(apples)代替算法.max

Collections.max 略有不同的声明:

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

这篇关于问题&lt; T extends Comparable&lt ;?超级T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆