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