这个题目有两种解法,第一种利用反射来解决:

//ArrayList<Integer> list = new ArrayList<Integer>();
//在这个泛型为Integer的ArrayList中存放一个String类型的对象。
public class Demo7 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        try {
            Class clazz=list.getClass();
            Method me=clazz.getMethod("add",Object.class);
            me.invoke(list, "abc");
            System.out.println(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  第二种可以利用新建一个没有泛型的引用,然后通过此引用绕开泛型的限制:

public class Demo7 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        ArrayList list2=list;
        list2.add("abc");
    }
}

 

相关文章:

  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-02
猜你喜欢
  • 2021-06-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案