簡體   English   中英

添加到集合中的元素應該是對象。 那么為什么要添加原始數據類型?

[英]Elements added to collection should be objects. Why can I add a primitive data type then?

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)並成功。 怎么樣? (在這種情況下,1是原始數據類型,而不是對象)

您的原始值將被裝箱到適當的包裝對象(Integer,Long等)中,並添加到Collection中,並且此功能是從Java 5添加的。

如果使用舊版本(Java 5之前的版本),在這種情況下會出現編譯錯誤。

1是自動裝箱的; 編譯器會為您處理。 發生的事情是,在運行時您添加的實際上是:

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

請注意,從List s中刪除 Integer是很棘手的,因為您有兩種刪除方法:一種是刪除給定索引( .remove(int) )的元素,另一種是刪除列表( .remove(T) )中的對象。

因此,如果要從列表中刪除對象 1 ,則必須.remove(Integer.valueOf(1)) ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM