Java19-5.2 泛型通配符及限定上下线
2019-01-15 本文已影响0人
第二套广播体操
public class Generic_Test6 {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
list.add("abc1");
list.add("abc2");
list.add("abc3");
list.add("abc4");
printCollection(list);
Set<String> set=new TreeSet<>();
set.add("abc1");
set.add("abc2");
set.add("abc3");
set.add("abc4");
printCollection(set);
}
private static void printCollection(Collection<String> collection) {
for (Iterator<String> iterator = collection.iterator(); iterator.hasNext(); ) {
String s = iterator.next();
System.out.println(s);
}
}
}
为了同时可以迭代两个集合 我们将迭代范围改到Collection
但是此时我们依然无法迭代类型为学生的集合
List<Student> list1=new ArrayList<>();
list1.add(new Student());
list1.add(new Student());
list1.add(new Student());
list1.add(new Student());
printCollection(list1);
所以我们引入通配符<?>
//通配符<?>不明确传递参数类型
private static void printCollection(Collection<?> collection) {
for (Iterator<?> iterator = collection.iterator(); iterator.hasNext(); ) {
Object o = iterator.next();
System.out.println(o);
}
}
上限应用
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;
public class Gerneric_Test7 {
public static void main(String[] args) {
ArrayList<MStudent> list=new ArrayList<>();
list.add(new MStudent("as",20));
list.add(new MStudent("a2",10));
list.add(new MStudent("as",19));
TreeSet<Student> set=new TreeSet<Student>(list);
for (Iterator<Student> iterator = set.iterator(); iterator.hasNext(); ) {
Student next = iterator.next();
System.out.println(next);
}
}
}
下限应用
public class Generic_Test8 {
public static void main(String[] args) {
Comparator<Student> comparator=new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int temp=o1.getName().compareTo(o2.getName());
return temp==0? o1.getAge()-o2.getAge():temp;
}
};
TreeSet<MStudent> set1=new TreeSet<>(comparator);
set1.add(new MStudent("asd1",12));
set1.add(new MStudent("zxcw",15));
set1.add(new MStudent("xczx",13));
set1.add(new MStudent("awqs",18));
TreeSet<HStudent> set2=new TreeSet<>(comparator);
set2.add(new HStudent("zxcz",12));
set2.add(new HStudent("qwes",14));
set2.add(new HStudent("zxwq",15));
set2.add(new HStudent("zxcw",23));
TreeSet<Student> set3=new TreeSet<>(comparator);
set3.addAll(set1);
set3.addAll(set2);
for (Iterator<Student> iterator = set3.iterator(); iterator.hasNext(); ) {
Student next = iterator.next();
System.out.println(next);
}
}
}