s-day02--泛型的通配符及其上下限
This commit is contained in:
@@ -0,0 +1,42 @@
|
|||||||
|
package com.inmind.generic_common05;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
/*
|
||||||
|
13.泛型通配符的使用(了解)
|
||||||
|
当我们想接收一个数据类型,它们的泛型不一致,但是方法中的操作是一致的时候,如果操作????
|
||||||
|
泛型通配符:?,它的作用是能够匹配任意的泛型类型,?使用时默认解析为Object
|
||||||
|
|
||||||
|
|
||||||
|
使用了通配符,还能限制传入的类型?
|
||||||
|
可以,受限泛型
|
||||||
|
|
||||||
|
格式:
|
||||||
|
<? extends B> :泛型的类型只能是B类型或者B类型的子类;上限
|
||||||
|
<? super B> : 泛型的类型只能是B类型或者B类型的父类;下限
|
||||||
|
*/
|
||||||
|
public class Demo08 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//创建2个集合对集合的内容进行遍历打印输出
|
||||||
|
ArrayList<Person> list1 = new ArrayList<>();
|
||||||
|
list1.add(new Person("张三1", 19));
|
||||||
|
list1.add(new Person("张三2", 18));
|
||||||
|
list1.add(new Person("张三3", 17));
|
||||||
|
|
||||||
|
showList(list1);
|
||||||
|
|
||||||
|
ArrayList<Student> list2 = new ArrayList<>();
|
||||||
|
list2.add(new Student("张三4", 19));
|
||||||
|
list2.add(new Student("张三5", 18));
|
||||||
|
list2.add(new Student("张三6", 17));
|
||||||
|
showList(list2);
|
||||||
|
}
|
||||||
|
|
||||||
|
//定义一个接收集合,对集合进行编译输出的方法
|
||||||
|
public static void showList(ArrayList<? extends Person> list){//泛型的上限
|
||||||
|
// public static void showList(ArrayList<? super Person> list){//泛型的下限
|
||||||
|
for (Person p : list) {
|
||||||
|
System.out.println(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.inmind.generic_common05;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
String name;
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public Person(String name, int age) {
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.inmind.generic_common05;
|
||||||
|
|
||||||
|
public class Student extends Person{
|
||||||
|
public Student(String name, int age) {
|
||||||
|
super(name, age);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user