2016-01-22 183 views
0

好的,我是Java新手,我只是在通过一个类来工作,而且我在类的程序中遇到了一些障碍。除了最后一件事情之外,我已经设法通过我最终节目中的每一部分工作。ArrayList.remove不能与Integer一起使用,与常量一起工作

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); 

它只是删除完美。

foundLocationInteger

有人可以向我解释我在这里做了什么吗?

我认为对于熟悉Java的人来说这是非常明显的,但我很想念它。

回答

3

这是一个讨厌的重载,偷偷进入Collections API设计。

有两种方法remove,一个用int打电话,一个用Object打电话,他们做的事情很不一样。

不幸的是,你Integer也是Object,即使你想使用它作为一个int(和做,在其他几个地方,由于自动装箱的魔力,遗憾的是不为remove工作)。

remove(1)将通过索引(第2个元素)删除。

remove(Integer.valueOf(1))将通过其值(列表中的第一个“1”)移除该对象。

给这两个方法两个不同的名字可能会更明智一些。

就你而言,请将foundPosition更改为int

+0

是的,这是一个类。我对这个方法的命名没有任何意见。如果我有选择,我会用Python编写它。明天一旦我更清醒一点(并清醒过来),我会看看这个,看看你的Integer.valueOf是否会解决这个问题。假设我可以做Integer.valueOf(foundLocation)。 –

+0

不! Integer.valueOf是问题的演示,而不是解决方案。您需要将'Integer foundLocation = 0;'更改为'int foundLocation = 0;' – Thilo

+0

...我认为那样做了。我不知道为什么人们说Java是一种不友好的语言(他讽刺地说)。非常感谢你的帮助,每个人。 –

0

ArrayList有两个remove方法,一个是remove(int index),另一个是remove(Object object), 你foundLocation类型是Integer,使用它时,这将是一个参考,所以,当你调用remove(foundLocation)它会调用remove(Object),试图找到一个元素== foundLocation,它找不到这个,所以一旦将类型更改为int,它将删除索引foundLocation处的元素,请参阅方法doc

0

ArrayList类中有两个'remove'方法。一个接受一个Object类型,另一个接受一个int类型。通过使用Integer对象,您可以在列表中找到与Integer对象相等的元素。但是,当您用int类型移除时,您正在移动列表中元素的位置。

studentList.remove(foundLocation)将导致ArrayList检查Integer对象,该对象等于foundLocation引用的对象。这是一个对象相等检查。即使它们具有相同的数值,具有相同值的两个不同的Integer对象也被视为不同。

studentList.remove(3)将导致ArrayList删除列表中的第四个元素。

相关问题