【问题标题】:Difference between ArrayList<Integer> iList = new ArrayList<Integer>(); and ArrayList iList = new ArrayList<Integer>(); [duplicate]ArrayList<Integer> iList = new ArrayList<Integer>(); 的区别和 ArrayList iList = new ArrayList<Integer>(); [复制]
【发布时间】:2019-01-03 07:10:26
【问题描述】:

这两行有什么区别:

ArrayList<Integer> iList = new ArrayList<Integer>();
ArrayList iList = new ArrayList<Integer>();   

第 1 步:引发编译时错误

public static void main(String args[]){
    ArrayList<Integer> iList = new ArrayList<Integer>();
    iList.add(10);
    iList.add("Test_Element"); // Compiler error, while trying to insert a String in an Integer ArrayList 
    System.out.print("Value of 2nd element: " + iList.get(1));
 }

第 2 步:工作正常

public static void main(String args[]){
    ArrayList iList = new ArrayList<Integer>();
    iList.add(10);
    iList.add("Test_Element"); // works fine, while trying to insert a String in an Integer ArrayList 
    System.out.print("Value of 2nd element: " + iList.get(1));
 } 

输出: 第二个元素的值:Test_Element

我预计会出现类似的错误

“ArrayList 中的 add(java.lang.Integer) 无法应用于 (java.lang.String)”,但在第二步中它可以正常工作。

谁能解释一下,为什么我可以在这个列表中插入一个字符串。

【问题讨论】:

标签: java generics arraylist


【解决方案1】:

当您编写 ArrayList list = new ArrayList&lt;Integer&gt;() 时,没有对泛型类型 ArrayList 进行编译时检查。赋值表达式右侧的泛型类型基本被忽略。 ArrayList真的没有内部类型,只是 ArrayList&lt;T&gt; 中的 T 可以帮助您确保仅对列表中的 T 实例执行操作。

了解为什么要将整数和字符串混合在同一个 ArrayList 中会很有用——这里可能有设计味道 :)

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2011-10-21
    • 2013-05-20
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    相关资源
    最近更新 更多