簡(jiǎn)介
刪除集合中的元素业踢,有兩種刪除的形式,一種是刪除特定元素礁扮,一種是刪除特定索引的元素知举。
刪除的方式有:使用Java API (java 8)、從后往前的循環(huán)太伊、使用迭代器雇锡、使用新的集合。
Java API
-
List#remove(int index)
僚焦。最基本API锰提,刪除特定索引處元素,O(1)芳悲。 -
List#remove(Object o)
立肘。從前往后遍歷,移除第一個(gè)與o
相等的元素名扛,O(n)谅年。 -
Collection#removeIf(Predicate<? super E> filter)
。移除所有特定元素肮韧,內(nèi)部使用迭代器融蹂;Java 8;O(n)弄企。 -
ArrayList#removeIf(Predicate<? super E> filter)
超燃。移除所有特定元素,內(nèi)部使用BitSet
標(biāo)記待刪除元素桩蓉;Java 8淋纲;O(n)。 -
List#subList(startIndex, endIndex).clear()
院究。刪除特定索引區(qū)間的元素洽瞬,O(n)本涕。
從后往前循環(huán)
適用兩種形式:刪除特定元素,以及刪除特定索引的元素伙窃。
// 刪除所有特定元素
for (int index = list.size() - 1; index >= 0; index --) {
Object element = list.get(index);
if (special.equals(element)) {
list.remove(index);
}
}
// 刪除多個(gè)特定索引的元素 比如菩颖,刪除索引在[start, end]內(nèi)的元素
for (int index = end; index >= start; index --) {
list.remove(index);
}
使用迭代器
適用刪除特定元素;部分(元素可標(biāo)記)適用刪除特定索引元素为障,先標(biāo)記再迭代刪除晦闰。
// 刪除所有特定元素
Iterator<Integer> iterator = list.listIterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
if (special.equals(element)) {
iterator.remove();
}
}
// 刪除特定索引元素,元素可標(biāo)記鳍怨,比如元素里的ID不能為負(fù)數(shù)呻右,標(biāo)記為負(fù)數(shù)即為待刪除元素
// 比如刪除索引在[start, end]中的整數(shù),如果集合不為負(fù)數(shù)鞋喇,則可以標(biāo)記待刪除元素為負(fù)數(shù)声滥。
for (int index = start; index <= end; index ++) {
list.set(index, Integer.MIN_VALUE);
}
Iterator<Integer> iterator = list.listIterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
if (element == Integer.MIN_VALUE) {
iterator.remove();
}
}
使用新的集合
創(chuàng)建新的集合,循環(huán)將舊集合中有效元素添加到新集合中侦香。在實(shí)踐中也較常用落塑。
總結(jié)
實(shí)踐中,各種方法的復(fù)雜度都相同罐韩,使用新的集合需要額外的空間憾赁,如果集合比較大則效率較低。
優(yōu)先考慮使用API散吵,不能滿足的情況下再考慮向前循環(huán)龙考、迭代或創(chuàng)建新的集合。