Java学习笔记之泛型(五):泛型的上下限

来源:互联网 发布:focusky破解补丁mac 编辑:程序博客网 时间:2024/05/17 08:59
package com.collection.genericity;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;/*泛型的上下限:需求1:定义一个方法可以接收任意类型的集合对象,要求接收的集合对象只能存储Integer或者是Integer的父类类型数据;需求2:定义一个方法可以接收任意类型的集合对象,要求接收的集合对象只能存储Number或者是Number的子类类型数据;泛型中的通配符:?;表示可以匹配任意的数据类型; */public class Demo7 {// 泛型的下限:// Collection<? super Integer>:表示任意的集合对象,存储的数据类型只能是Integer或者是Integer的父类;public static void test1(Collection<? super Integer> c){}// 泛型的上限:// Collection<? super Integer>:表示任意的集合对象,存储的数据类型只能是Integer或者是Integer的父类;public static void test2(Collection<? extends Number> c){}public static void main(String[] args) {ArrayList<Integer> list1 = new ArrayList<Integer>();ArrayList<Number> list2 = new ArrayList<Number>();HashSet<String> set = new HashSet<String>();// 要求1:test1()方法接收的集合对象只能存储Integer或者是Integer的父类类型数据;test1(list1);test1(list2);//test1(set);// 错误// 要求2:test2()方法接收的集合对象只能存储Number或者是Number的子类类型数据;test2(list1);test2(list2);//test2(set);// 错误}}

原创粉丝点击