您的位置:首页 > 其它

黑马程序-泛型高级应用-向上限定-向下限定

2015-01-16 15:36 113 查看
------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

泛型高级应用:
? 占位符 || 通配符

概念:当集合不确定将要接收什么类型的对象时,使用“?”作为接收未来传递来的对象的通配符。

? 占位符 || 通配符

格式:Collection<?> ... ...

缺点:不能使用对象的特有方法,这一点就是面向接口编程的缺点,可以通过强制转换来使用具体对象的特有方法。

package com.lxh.collection;
import java.util.*;
public class AdvancedGeneric {

public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("aa1");
al.add("aa2");
al.add("aa3");
AdvancedGeneric.printIterator(al);

ArrayList al2 = new ArrayList();
al2.add(3);
al2.add(4);
al2.add(6);
AdvancedGeneric.printIterator(al2);
}

/**
* 通配符方式。
* 缺点:不能使用对象中元素的特有方法了。
* */
public static void printIterator(ArrayList<?> al) {
Iterator it = al.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}

/**
* 泛型方式
* 缺点:不能使用对象中元素的特有方法了。
* */
public static  void printIterator2(ArrayList al) {
Iterator it = al.iterator();
T t = it.next();
System.out.println(t);
}
}


注意:在初始化泛型的集合时,引用类型和初始化类型需要保持一致。而不能像

如:ArrayList<Animal> al = new ArrayList<Dog>();

原因:在实例化时,声明了存放的内容为Dog,而声明类型是Animal。从多肽的角度来看,声明的al可以接收全部的Animal子类,但是在泛型的概念中,此集合只能接收Dog,所以存放其他Animal的子类,就会造成类型安全问题。

解决方法:左右的类型保持一致。

泛型限定
1. 向上限定

定义:?  extends  E : 只能存储E,或E的子类。

添加:以List的add方法为例。

package com.lxh.collection;
import java.util.*;
public class AdvancedGeneric {

public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new SuperMan("张三",23));
al.add(new SuperMan("张四",24));
al.add(new SuperMan("张五",25));
al.add(new SuperMan("张三",23));
AdvancedGeneric.printIterator(al);

TreeSet ts = new TreeSet();
ts.add(new SuperMan("张三",23));
ts.add(new SuperMan("张四",24));
ts.add(new SuperMan("张五",25));
ts.add(new SuperMan("张三",23));
AdvancedGeneric.printIterator(ts);
}

/**
* 通配符方式。
* 缺点:不能使用对象中元素的特有方法了。
* */
public static void printIterator(Collection<? extends Man> al) {
Iterator<? extends Man> it = al.iterator();
while(it.hasNext()) {
Man m = it.next();
System.out.println(m.getName());
}
}
}

2. 向下限定

定义:?  super  E : 只能存储E,或E的父类。

比较:以TreeSet的比较器为例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  泛型
相关文章推荐