黑马程序员技术交流社区
标题:
迭代泛型问题
[打印本页]
作者:
清风有意
时间:
2014-4-16 11:25
标题:
迭代泛型问题
为何我在Iterator<Integer> 已经声明了是Integer,但是还是可以打印出来字符"abc"呢?
package exercise;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
/**
* ArrayList<Integer> list = new ArrayList<Integer>();
* 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
* @author feaoes
*
*/
public class Test3 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
for(Integer it:list)
{
System.out.println(it);
}
try {
Method clazzMethod=ArrayList.class.getMethod("add", Object.class);
clazzMethod.invoke(list, "abc");
Iterator<Integer> it=list.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
复制代码
作者:
呆呆沙师妹
时间:
2014-4-16 14:55
据我所知:类型值信息只为Java编译器在编译时所使用,确保代码无类型安全问题,验证通过后即被去除,对JVM而言,集合跟1.5之前版本一样。
对于编译器来说:
ArrayList<Integer> list = new ArrayList<Integer>();
Iterator<Integer> it=list.iterator();
没有问题,编译就通过了,而运行时去掉了类型值信息,即
ArrayList list = new ArrayList();
其中的所有对象都可以用迭代器取出。
作者:
随风而去
时间:
2014-4-16 22:42
呆呆师妹很犀利啊,这个都有涉及,见识了..
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2