<T extends Comparable<T>>和<T extends Comparable<? super T>>含义

<T extends Comparable<T>>表明T实现了Comaprable<T>接口,此条件强制约束,泛型对象必须直接实现Comparable<T>(所谓直接就是指不能通过继承或其他方式)

<T extends Comparable<? super T>> 表明T的任意一个父类实现了Comparable<? super T>接口,其中? super T表示 ?泛型类型是T的父类(当然包含T),因此包含上面的限制条件,且此集合包含的范围更广

案例如下

  

   //    有限制的泛型  只允许实现Comparable接口的参数类型
//    从集合中找出最小值
    public static <T extends Comparable<T>> T min(List<T> list) {
        Iterator<T> iterator = list.iterator();
        T result = iterator.next();
        while (iterator.hasNext()) {
            T next = iterator.next();
            if (next.compareTo(result) < 0) {
                result = next;
            }
        }
        return result;
    }

    //    <T extends Comparable<? super T>> 限制
//    此方法 多一个 ? super T 约束 表明可以是T或者T的某个父类实现Comparable接口
    public static <T extends Comparable<? super T>> T min2(List<T> list) {
        Iterator<T> iterator = list.iterator();
        T result = iterator.next();
        while (iterator.hasNext()) {
            T next = iterator.next();
            if (next.compareTo(result) < 0) {
                result = next;
            }
        }
        return result;
    }

  Dog.java

package com.effectJava.Chapter2;
public class Dog extends Animal {
    private int age;
    private String name;
    private String hobby;

    public Dog(int id,int age, String name, String hobby) {
        super(id);
        this.age = age;
        this.name = name;
        this.hobby = hobby;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public String getHobby() {
        return hobby;
    }

    public int getAge() {
        return age;
    }
}

  Animal.java

package com.effectJava.Chapter2;

public class Animal implements Comparable<Animal> {

    //    唯一标识动物的id
    protected int id;

    public Animal(int id) {
        this.id = id;
    }

    public Animal() {

    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    @Override
    public int compareTo(Animal o) {
        return this.getId() - o.getId();
    }
}

  运行main函数

  List<Dog> dogs = new ArrayList<>();
        dogs.add(new Dog(1, 1, "1", "1"));
        dogs.add(new Dog(2, 2, "2", "2"));
        dogs.add(new Dog(3, 3, "3", "3"));
//        编译错误 由于Dog没有直接实现Comparable<Dog>接口
        min(dogs);
//        由于Dog父类Animal实现了Comparable<Dog>接口
        min2(dogs);

  

posted @ 2018-01-20 09:40  张秀杰  阅读(938)  评论(0编辑  收藏  举报