经验教训:
list的remove(object obj)方法无法删除元素
ArrayList的remove(Object obj)的源码:
public boolean remove(Object o) {
if(o == null) {
for(int index = 0; index < size; index++)
if(elementData[index] == null) {
fastRemove(index);
return true;
}
}else{
for(int index = 0; index < size; index++)
if(o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
01.源码中的`o.equals(elementData[index]`说明remove()方法删除元素的时候,需要使用两个元素的equals()方法
02.如果没有写明element的equals()方法,就会出现remove()方法删除不了元素或者乱删除元素的情况
03.kotlin中使用equals()方法和hashCode()方法的实例:
data class addressListBean(val name: String? = null, val sex: String? = null): Parcelable{
override fun equals(other: Any?): Boolean {
if(this == other){
return true
}
if(other == null){
return false;
}
val addressListBean = other as AddressListBean
//使用name作为判断addressListBean是否相同的元素
return name == addressListBean.name
}
//生成addressListBean中name的hashCode值
override fun hashCode(): Int {
return name.hashCode()
}