LearningNotes icon indicating copy to clipboard operation
LearningNotes copied to clipboard

2、当集合里面的对象属性被修改后,再调用remove()方法时不起作用。实测,有用。

Open aheadlcx opened this issue 7 years ago • 3 comments

如题,实测有用。作者愿意提供一下你的测试场景。

aheadlcx avatar Jul 28 '16 07:07 aheadlcx

public class Person { String string; String string2;int i; public Person(String string, String string2, int i) { this.string=string; this.string2=string2; this.i=i; }

public void setAge(int i)
{
 this.i=i;

}

@Override
public int hashCode()
{
    final int prime = 31;
    int result = 1;
    result = prime * result + i;
    result = prime * result + ((string == null) ? 0 : string.hashCode());
    result = prime * result + ((string2 == null) ? 0 : string2.hashCode());
    return result;
}

@Override
public boolean equals(Object obj)
{
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Person other = (Person) obj;
    if (i != other.i)
        return false;
    if (string == null)
    {
        if (other.string != null)
            return false;
    }
    else if (!string.equals(other.string))
        return false;
    if (string2 == null)
    {
        if (other.string2 != null)
            return false;
    }
    else if (!string2.equals(other.string2))
        return false;
    return true;
}

} 修改后 实测 无用

duanshengze avatar Aug 01 '16 09:08 duanshengze

本人也刚刚测试了,不重写hashcode方法,怎么修改对象属性,对象的hashcode值都不会改变,所以该例对象一直是4个。所以这种说法是不是错误的啊

andyhaha avatar Sep 25 '16 01:09 andyhaha

要注意hashcode和equals是捆绑使用的

Guolei1130 avatar Dec 27 '16 16:12 Guolei1130