Java集合的 contains( ) 执行流程

Java集合的 contains( ) 执行原理

1 问题描述

想让classID一样的class对象的classTime叠加起来,目前是分开存放在list中

方案:

  • 手动遍历
  • 利用List或者Set的contains( )去重
  • 改成用HashMap存放,key为ID,轻松解决问题 (不过这方法后来才想到)
2 ArrayList的contains
  • 基于ArrayList测试

  • 需要重写equals方法

  • 基于 java 11

  • ArrayList在contains方法中会调用ArrayList本身的indexOf方法来遍历

    /**
     * Returns {@code true} if this list contains the specified element.
     * More formally, returns {@code true} if and only if this list contains
     * at least one element {@code e} such that
     * {@code Objects.equals(o, e)}.
     *
     * @param o element whose presence in this list is to be tested
     * @return {@code true} if this list contains the specified element
     */
public boolean contains(Object o) {
   
        return indexOf(o) >= 0;
    }

  • 该类下的indexOf会从头到尾遍历整个List,从中寻找对象 o
  • 比较的方式是用对象o重写过后的 **equals()**方法,如String
  • 若对象o未重写equals方法,则是Object下的equals的方法,比较对象的地址
/**
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index {@code i} such that
 * {@code Objects.equals(o, get(i))},
 * or -1 if there is no such index.
 */
public int indexOf(Object o) {
   
    return indexOfRange(o, 0, size);
}

int indexOfRange(Object o, int start, int end) {
   
    Object[] es = elementData;
    if (o == null) {
   
        for (int i = start; i < end; i++) {
   
            if (es[i] == null) {
   
                return i;
            }
        }
    } else {
   
        for (int i = start; i < end; i++) {
   
            if (o.equals(es[i])) {
   
                return i;
            }
        }
    }
    return -1;
}
3 HashSet 的 contains
  • HashSet中大部分操作都是借用HashMap来操作,contains也不例外

  • contains (hashset本身)—> containsKey(HashMap) --> getNode(HashMap)<–> hash(HashMap) —> hashCode(对象本身 或者 默认实现)

  • /**
     * Returns {@code true} if this set contains the specified element.
     * More formally, returns {@code true} if and only if this set
     * contain
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值