java 泛型的通配符和限定

package cn.sasa.demo1;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class ListDemo {
    public static void main(String[] args) {
        //泛型的通配符 ?
        Collection<String> strColl = new ArrayList<String>();
        Collection<Integer> intColl = new ArrayList<Integer>();
        
        strColl.add("hahaha");
        intColl.add(111);
        
        //strColl 和 intColl 都可以成为 printColl方法的参数,因为<>里写了通配符?,匹配所有的数据类型
        printColl(strColl);
        printColl(intColl);
        
        //泛型的限定
        //如果<>里用?匹配所有的类型,会有安全隐患
        //设计一个方法,使其可以调用Dog类的集合和Cat类的集合中元素的speak()方法
        Collection<Dog> dogColl = new ArrayList<Dog>();
        dogColl.add(new Dog("Wangcai",4));
        dogColl.add(new Dog("aHuang",3));
        
        Collection<Cat> catColl = new ArrayList<Cat>();
        catColl.add(new Cat("Kittey",6));
        catColl.add(new Cat("Ruby",2));
        
        speak(dogColl);
        speak(catColl);
        
        //Collection<String> testColl = new ArrayList<String>();
        //testColl.add("qqq");
        //speak(testColl);//报错,因为testColl里的元素不是Animal的子类
        
    }
    /**
     * 使不同的泛型集合都可以调用这个方法
     * 泛型的通配符 ?
     */
    static void printColl(Collection<?> coll) {
        Iterator<?> it = coll.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }
    
    /**
     * ? extends 限定为某个类的子类
     * ? super 限定为某个类的父类
     */
    static void speak(Collection<? extends Animal> coll) {
        Iterator<? extends Animal> it = coll.iterator();
        while(it.hasNext()) {
            Animal animal = it.next();
            animal.speak();
        }
    }
}
package cn.sasa.demo1;

public abstract class Animal {
    private String type;
    private int age;
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public abstract void speak();
}
package cn.sasa.demo1;

public class Dog extends Animal{
    
    public Dog(String type, int age) {this.setType(type);
        this.setAge(age);
    }
    @Override
    public void speak() {
        System.out.println(this.getType() + " Wang wang");
    }

}
package cn.sasa.demo1;

public class Cat extends Animal{

    public Cat(String type, int age) {this.setType(type);
        this.setAge(age);
    }
    @Override
    public void speak() {
        System.out.println(this.getType() + " Mellow mellow");
    }

}
原文地址:https://www.cnblogs.com/SasaL/p/10142976.html