添加到集合中的元素应该是对象.为什么我可以添加原始数据类型呢?


import java.util.*;
       class Ball{
         public static void main(String args[])
         {
            ArrayList <Integer> al = new ArrayList<Integer>();
            al.add(new Integer(1));
            System.out.println(al);
            }   
         }

我正在阅读Herbert Schildt的完整参考Java 2,我看到了这个片段。上面写着

The program begins by creating a collection of integers.

You cannot store primitive data types in a collection

 so objects of type Integer are created and stored.

然而,我尝试使用al.add(1),它的工作原理。如何?

您的原始值将被装箱到适当的包装对象(Integer, Long等)并添加到Collection中,该功能从java 5中添加。

如果您使用旧版本(Java 5之前),在这种情况下您将得到编译错误。

1是autobox;编译器会替你处理这个问题。实际情况是,在运行时你的add实际上是:

al.add(Integer.valueOf(1));

请注意,Integer s List s中删除是棘手的,因为您有两个 remove方法:一个删除给定索引上的元素(.remove(int)),一个删除列表中的对象(.remove(T))。

所以,如果你想从你的列表中删除对象 1你必须.remove(Integer.valueOf(1))

相关内容

最新更新