一、遍歷集合List的五種方法
測(cè)試數(shù)據(jù)
List<String> list = new ArrayList<>();
list.add("A");list.add("B");list.add("C");
1. 普通for循環(huán)
普通for循環(huán),通過索引遍歷
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
2. 增強(qiáng)for循環(huán)
增強(qiáng)for循環(huán),數(shù)組以及所有Collection集合都可以使用增強(qiáng)for循環(huán)遍歷。遍歷集合的實(shí)際原理為獲取集合的iterator迭代器對(duì)象進(jìn)行迭代遍歷。
for (String s : list) {
System.out.println(s);
}
3. Iterator迭代器遍歷
Collection接口繼承自Iterable接口,所有Collection集合都必須實(shí)現(xiàn)iterator()方法返回一個(gè)Iterator迭代器對(duì)象。因此可以通過list的iterator()方法獲取迭代器對(duì)象來進(jìn)行遍歷。并且可在迭代過程中調(diào)用iterator.remove()安全移除當(dāng)前元素。
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("B")) iterator.remove();
System.out.println(s);
}
4. ListIterator迭代器遍歷
所有List集合都必須實(shí)現(xiàn)一個(gè)listIterator()方法,返回一個(gè)ListIterator迭代器對(duì)象。ListIterator 是 Iterator 的子接口,除了可以從前往后遍歷外,還可以反向遍歷,即從后往前遍歷。還可以在遍歷過程中使用listIterator.add()方法在當(dāng)前遍歷位置之后插入元素,使用listIterator.set() 方法修改當(dāng)前元素,以及使用listIterator.remove()移除當(dāng)前元素。
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
String element = listIterator.next();
if (element.equals("B")) {
// 修改當(dāng)前元素
listIterator.set("D");
// 在當(dāng)前元素后面插入一個(gè)新元素
listIterator.add("E");
//將迭代器指針移動(dòng)到前一個(gè)元素,然后進(jìn)行刪除
listIterator.previous();
listIterator.remove();
}
}
System.out.println(list); // 輸出 [A, D, C]
5. list.forEach(lambda表達(dá)式)
list.forEach(element -> {
// 使用 element
System.out.println(element);
});
二、如何在遍歷集合過程中安全移除元素
如果在使用 Iterator 或 ListIterator 遍歷集合的過程中,使用了list.remove() 方法來移除元素,而沒有通過迭代器自身的 remove() 方法,就有可能導(dǎo)致 ConcurrentModificationException。這是因?yàn)閘ist內(nèi)部維護(hù)了一個(gè)修改計(jì)數(shù)器modCount, 記錄list中添加和刪除元素的次數(shù),迭代器對(duì)象內(nèi)部會(huì)維護(hù)一個(gè)迭代器修改計(jì)數(shù)器expectedModCount,如果被非迭代器方法修改了list,導(dǎo)致modCount增加了而expectedModCount沒有增加,導(dǎo)致二者不想等于是在check時(shí)拋出異常。文章來源:http://www.zghlxwxcb.cn/news/detail-636105.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-636105.html
- 因此在增強(qiáng)for循環(huán)中不能添加或移除元素。
- 需要使用Iterator 或 ListIterator 來迭代遍歷集合,并且使用迭代器的方法來移除或添加元素。
到了這里,關(guān)于遍歷集合List的五種方法以及如何在遍歷集合過程中安全移除元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!