记一次list删除操作的重要失误

26 篇文章 0 订阅
26 篇文章 0 订阅

经验教训:

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()
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值