LearningNotes
LearningNotes copied to clipboard
2、当集合里面的对象属性被修改后,再调用remove()方法时不起作用。实测,有用。
如题,实测有用。作者愿意提供一下你的测试场景。
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;
}
} 修改后 实测 无用
本人也刚刚测试了,不重写hashcode方法,怎么修改对象属性,对象的hashcode值都不会改变,所以该例对象一直是4个。所以这种说法是不是错误的啊
要注意hashcode和equals是捆绑使用的