T extends ComparableT和T extends Comparable? super T含义
生活随笔
收集整理的這篇文章主要介紹了
T extends ComparableT和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> {// 唯一標識動物的idprotected int id;public Animal(int id) {this.id = id;}public Animal() {}public void setId(int id) {this.id = id;}public int getId() {return id;}@Overridepublic 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);
轉載于:https://www.cnblogs.com/09120912zhang/p/8319899.html
總結
以上是生活随笔為你收集整理的T extends ComparableT和T extends Comparable? super T含义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring注解方式实现定时器
- 下一篇: 338. Counting Bits(动