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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 微微微笑 中级黑马   /  2014-10-24 16:32  /  956 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

为什么可以向Integer型的ArrayList中加入String类型,而不可以向String类型的ArrayList中加入Integer
package com.itheexam;

import java.lang.reflect.Method;
import java.util.ArrayList;

public class Test4 {

        public static void main(String[] args) throws Exception, NoSuchMethodException {
                // TODO Auto-generated method stub
                /*
                 * Integer的ArrayList可以通过反射,向里面加入String类型数据
                ArrayList<Integer> list=new ArrayList<Integer>();
                Method method=list.getClass().getMethod("add", Object.class);
                method.invoke(list, "abc");
                System.out.println(list.get(0));
                */
                //但这段代码会出错
                ArrayList<String> list=new ArrayList<String>();
                Method method=list.getClass().getMethod("add", Object.class);
                method.invoke(list, 1);
                System.out.println(list.get(0));
               

        }

}

1 个回复

倒序浏览
之前也遇到过 以为自己写错了 没怎么在意 还好你现在提出来了 坐等高人指点
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马