[英]ArrayList.remove not working with Integer, works with constant
好吧,我是Java的新手,我正在上一堂課,並且在上課的程序上遇到了一些麻煩。 除了最后一件事,我已經設法完成了最終程序的每一部分。
public static void remove(String studentID)
{
Integer foundLocation = 0;
for (int i = 0; i < studentList.size(); i++)
{
if (studentList.get(i).getStudentID().compareTo(studentID) == 0)
{
//This means we have found our entry and can delete it
foundLocation = i;
}
}
System.out.println(foundLocation);
if (foundLocation != 0)
{
System.out.println(studentList);
studentList.remove(foundLocation);
System.out.println(foundLocation.getClass().getName());
System.out.println("Student ID removed: " + studentID);
System.out.println(studentList);
}
else
{
System.out.println("Sorry, " + studentID + " not found.");
}
該代碼似乎應該工作。 但是,我得到的是remove
實際上並沒有執行任何操作。 我的多余照片在那里驗證。 普通的ArrayList
不會改變。
但是,如果我只是替換:
studentList.remove(foundLocation);
與類似:
studentList.remove(3);
它只是刪除完美。
foundLocation
是一個Integer
。
有人可以告訴我我在這里發生了什么嗎?
我希望它對熟悉Java的人來說是顯而易見的,但是我很想念它。
這有點令人討厭,它隱藏在Collections API設計中。
有兩種remove
方法,一種是用int
調用的,另一種是用Object
調用的,它們的作用截然不同。
不幸的是,即使您想將Integer
用作int
, Integer
也是一個Object
(並且在其他幾個地方也可以使用int
,這要歸功於自動裝箱的魔力,但不幸的是,它不能用於remove
)。
remove(1)
將按索引(第二個元素)刪除。
remove(Integer.valueOf(1))
將通過對象的值(在列表中找到的第一個“ 1” remove(Integer.valueOf(1))
刪除對象。
為這兩種方法提供兩個不同的名稱可能會更明智。
在您的情況下,將foundPosition
更改為int
。
ArrayList
有兩個remove
方法,一個是remove(int index) ,另一個是remove(Object object) ,您的foundLocation
類型是Integer
,當使用它時將是一個引用,因此當您調用remove(foundLocation)
時它將調用remove(Object)
,嘗試找到一個元素== foundLocation,找不到它,因此什么也不要刪除,一旦將類型更改為int,它將刪除索引foundLocation處的元素,請參考doc方法。
ArrayList類中有兩個“刪除”方法。 一個接受對象類型,另一個接受int類型。 通過使用Integer對象,可以在列表中找到與Integer對象相等的元素。 但是,當您按int類型刪除時,您將按元素在列表中的位置移動。
studentList.remove(foundLocation)將導致ArrayList檢查一個Integer對象,該對象等於foundLocation引用的對象。 這是一個對象相等性檢查。 即使兩個具有相同值的不同Integer對象具有相同的數值,也將被視為不同。
studentList.remove(3)將導致ArrayList刪除列表中的第四個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.