繁体   English   中英

ArrayList.remove不与Integer一起使用,与常量一起使用

[英]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用作intInteger也是一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM