2016-11-25 41 views
0

我有下面的代码,并且我已经在覆盖equals()hashCode()方法ContainerBean上放置了断点。当我在调试模式下在应用程序下运行时,调试器仅在行停止,而不是在尝试从List删除元素时停止在System.out.println行。在Eclipse中调试equals()和hashCode()

import java.util.ArrayList; 
import java.util.List; 

public class ListRemovalDriver { 

    public static void main(String[] args) { 
     List<ContainerBean> remitClaims = new ArrayList<>(); 

     ContainedBean addedRemit1 = new ContainedBean(); 
     addedRemit1.setRemitId(12345L); 
     ContainerBean added1 = new ContainerBean(); 
     added1.setRemitBean(addedRemit1); 

     remitClaims.add(added1); 

     ContainedBean removedRemit1 = new ContainedBean(); 
     removedRemit1.setRemitId(12345L); 
     ContainerBean removed1 = new ContainerBean(); 
     removed1.setRemitBean(removedRemit1); 

     System.out.println("List before valid removal" + remitClaims); 

     remitClaims.remove(removed1); 

     System.out.println("List after valid removal" + remitClaims); 



    } 
} 

我错过了什么吗?

将被覆盖equals()ContainerBean从列表中删除元素时不会被调用?

编辑

我忘了提,hashCode()equals()预期,即元素越来越为每equals()逻辑,但它仅是不把我那里名单删除函数调用调试器除去正在工作。从JDK 7的ArrayList

回答

1

会覆盖不会调用ContainerBean中的equals() 从列表中删除元素?

是的,当您使用remove(Object o),然后equals()ContainerBean将被要求检查对象的平等,然后根据下面的ArrayList API(重点煤矿)中提到,从列表中删除:

删除此列表中第一次出现的指定元素,如果它存在,则删除 。如果列表中不包含该元素,则不更改为 。更正式地,删除具有最低索引i的元素,使得(o == null?get(i)== null:o.equals(get(i)))(如果存在这样的 元素)。如果此列表包含指定的 元素(或等效地,如果此列表因 调用而更改),则返回true。

但是,在另一侧上,当要卸下使用列表的索引的元素(即,使用remove(int index)),那么不会有任何equals()检查。

你可以看看here

+0

正如我的代码所示,我不是通过索引删除,而是传递一个对象来删除。对象被成功移除,但是它唯一的Eclipse调试器在那个事件中没有带我去那里。 –

+0

我知道,我刚刚添加了这一点,让你明白其中的差异。 – developer

1

源代码,

ArrayList.remove(Object o) 

它调用等于方法来验证对象从集合中移除

for (int index = 0; index < size; index++) 
    if (o.equals(elementData[index])) { 
     fastRemove(index); 
     return true; 
    } 
} 

源:ArrayList Source

2

因为你没有给我猜码:你没有重载equals,而是加入一个像这样的超载:

public boolean equals(ContainerBean c) { ... } 

这不会因为工作调用equals(Object)。

更改您的equals实现以获取Object类型的参数,并且它将被调用并停在eclipse调试器中。

+0

我已覆盖它。以“对象”作为参数。 –

+0

然后你必须显示你的代码。 'ArrayList.remove(Object)'调用'equals()'如果列表不为空且参数不是'null'。 – Axel

+0

PS:也许你不小心设置'等于()''中的ContainedBean'代替'ContainerBean'断点?你应该在包含调用remove()的行上放置一个断点,然后进入该方法来找出结果。 – Axel