<T extends Comparable<T>>代表T实现了Comaprable<T>接口,此条件强制约束,泛型对象必须直接实现Comparable<T>(所谓直接就是指不能经过继承或其余方式)java
<T extends Comparable<? super T>> 代表T的任意一个父类实现了Comparable<? super T>接口,其中? super T表示 ?泛型类型是T的父类(固然包含T),所以包含上面的限制条件,且此集合包含的范围更广ide
案例以下函数
// 有限制的泛型 只容许实现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.javathis
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函数blog
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);