s-day02-泛型通配符的使用(了解)
This commit is contained in:
@@ -0,0 +1,33 @@
|
|||||||
|
package com.inmind.generic_tpf08;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
/*
|
||||||
|
13.泛型通配符的使用(了解) ?
|
||||||
|
当我们要接受一个数据类型,它的泛型不一致,要使用泛型通配符,匹配?
|
||||||
|
*/
|
||||||
|
public class Demo10 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//创建人和学生的2个集合
|
||||||
|
ArrayList<Person> list1 = new ArrayList<>();
|
||||||
|
list1.add(new Person("小王1", 18));
|
||||||
|
list1.add(new Person("小王2", 18));
|
||||||
|
//遍历打印集合中的内容
|
||||||
|
showList(list1);
|
||||||
|
|
||||||
|
ArrayList<Student> list2 = new ArrayList<>();
|
||||||
|
list2.add(new Student("小王3", 18));
|
||||||
|
list2.add(new Student("小王4", 18));
|
||||||
|
//遍历打印集合中的内容
|
||||||
|
showList(list2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
ArrayList<Object> 这样写的话是错的,泛型是没有多态的
|
||||||
|
*/
|
||||||
|
public static void showList(ArrayList<?> list){
|
||||||
|
for (Object o : list) {
|
||||||
|
System.out.println(o);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.inmind.generic_tpf08;
|
||||||
|
|
||||||
|
public class Person {
|
||||||
|
String name;
|
||||||
|
int age;
|
||||||
|
|
||||||
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Person(String name, int age) {
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Person{" +
|
||||||
|
"name='" + name + '\'' +
|
||||||
|
", age=" + age +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.inmind.generic_tpf08;
|
||||||
|
|
||||||
|
public class Student extends Person{
|
||||||
|
|
||||||
|
public Student() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student(String name, int age) {
|
||||||
|
super(name, age);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Student{" +
|
||||||
|
"age=" + age +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user