泛型通配符:
public class GenericDemo7 {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("abc1",20));
list.add(new Student("abc2",21));
list.add(new Student("abc3",22));
list.add(new Student("abc4",23));
printCollection(list);
Set<Work> set = new HashSet<Work>();
set.add(new Work("sssii",14));
set.add(new Work("abc",19));
set.add(new Work("cba",20));
printCollection(set);
}
private static void printCollection(Collection<?> coll) {//在不明确具体类型的情况下,可以使用通配符来表示
for (Iterator<?> it = coll.iterator(); it.hasNext();) {
Object obj = it.next();
System.out.println(obj);
}
}
}
泛型的限定:
? extends Person 泛型的上限
? super Person 泛型的下限
public class GenericDemo7 {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("abc1",20));
list.add(new Student("abc2",21));
list.add(new Student("abc3",22));
list.add(new Student("abc4",23));
printCollection(list);
Set<Work> set = new HashSet<Work>();
set.add(new Work("sssii",14));
set.add(new Work("abc",19));
set.add(new Work("cba",20));
printCollection(set);
}
/*
* 泛型的限定:
* ? extends E :接收E类型或者E的子类型。 泛型的上限
* ? super E :接收E类型或者E的父类型。 泛型的下限
*/
private static void printCollection(Collection<?extends Person> coll) {//在不明确具体类型的情况下,可以使用通配符来表示
for (Iterator<?extends Person> it = coll.iterator(); it.hasNext();) {
Person p = it.next();
System.out.println(p);
}
}
}
泛型的上限:
public class GenericDemo8 {
public static void main(String[] args) {
/*
* 演示泛型限定在API中的体现
* TreeSet的构造方法
* TreeSet(Collection<? extends E> coll)
* 什么时候用到上限呢?
* 一般往集合存储元素时,如果集合定义了E类型通常情况下应该存储E类型的对象。
* 对于E的子类型的子对象B类型的对象B也可以接受,所以这时可以将泛型从E改为? extends E.
*/
Collection<Student> coll = new ArrayList<Student>();
coll.add(new Student("xiaoming",25));
coll.add(new Student("dabao",15));
coll.add(new Student("lala",65));
Collection<Work> wo = new ArrayList<Work>();
wo.add(new Work("宝宝1",12));
wo.add(new Work("宝宝2",12));
wo.add(new Work("宝宝3",12));
TreeSet<Person> ts = new TreeSet<Person>(coll);
ts.addAll(wo);
for (Iterator<Person> it = ts.iterator(); it.hasNext();) {
Person person = it.next();
System.out.println(person);
}
}
}
泛型的下限:
public class GenericDemo9 {
public static void main(String[] args) {
/*
* 演示泛型限定在API中的体现
* TreeSet的构造方法
* TreeSet(Collection<? super E> coll)
* 什么时候用到下限呢?
* 当从容器中取出元素操作时,可以用E类型接受,也可以用E的父类型接受
*/
//创建一个比较器
Comparator<Person> comp = new Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
int temp = o1.getAge()-o2.getAge();
return temp==0?o1.getName().compareTo(o2.getName()):temp;
}};
TreeSet<Student> ts = new TreeSet<Student>(comp);
ts.add(new Student("xiaoming",25));
ts.add(new Student("dabao",15));
ts.add(new Student("lala",65));
TreeSet<Work> tsl = new TreeSet<Work>(comp);
tsl.add(new Work("lihua",23));
tsl.add(new Work("xxx",10));
tsl.add(new Work("niuniu",21));
for (Iterator<Work> it = tsl.iterator(); it.hasNext();) {
Work student = it.next();
System.out.println(student);
}
}
}
关注我的微信公众号(曲健磊的个人随笔),观看更多精彩内容: