A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 清风有意 中级黑马   /  2014-4-16 11:25  /  829 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

为何我在Iterator<Integer> 已经声明了是Integer,但是还是可以打印出来字符"abc"呢?

  1. package exercise;


  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.util.ArrayList;
  5. import java.util.Iterator;


  6. /**
  7. * ArrayList<Integer> list = new ArrayList<Integer>();
  8. * 在这个泛型为Integer的ArrayList中存放一个String类型的对象。
  9. * @author feaoes
  10. *
  11. */

  12. public class Test3 {

  13.         public static void main(String[] args) {
  14.                 ArrayList<Integer> list = new ArrayList<Integer>();
  15.                 list.add(1);
  16.                 list.add(2);
  17.                 for(Integer it:list)
  18.                 {
  19.                         System.out.println(it);
  20.                 }
  21.                
  22.                
  23.                         try {
  24.                                 Method clazzMethod=ArrayList.class.getMethod("add", Object.class);
  25.                                 clazzMethod.invoke(list, "abc");
  26.                                 Iterator<Integer> it=list.iterator();
  27.                                 while(it.hasNext())
  28.                                 {       
  29.                                         System.out.println(it.next());
  30.                                 }
  31.                         } catch (NoSuchMethodException e) {
  32.                                 e.printStackTrace();
  33.                         } catch (SecurityException e) {
  34.                                 e.printStackTrace();
  35.                         } catch (IllegalAccessException e) {
  36.                                 e.printStackTrace();
  37.                         } catch (IllegalArgumentException e) {
  38.                                 e.printStackTrace();
  39.                         } catch (InvocationTargetException e) {
  40.                                 e.printStackTrace();
  41.                         }
  42.                        
  43.                        
  44.                
  45.                
  46.         }

  47. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

2 个回复

倒序浏览
据我所知:类型值信息只为Java编译器在编译时所使用,确保代码无类型安全问题,验证通过后即被去除,对JVM而言,集合跟1.5之前版本一样。
对于编译器来说:
ArrayList<Integer> list = new ArrayList<Integer>();
Iterator<Integer> it=list.iterator();
没有问题,编译就通过了,而运行时去掉了类型值信息,即
ArrayList list = new ArrayList();
其中的所有对象都可以用迭代器取出。




评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

回复 使用道具 举报 1 0
呆呆师妹很犀利啊,这个都有涉及,见识了..
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马