Java List的remove()方法踩坑
Java的List在刪除元素時(shí),一般會(huì)用list.remove(o)/remove(i)方法。在使用時(shí),容易觸碰陷阱,得到意想不到的結(jié)果??偨Y(jié)以往經(jīng)驗(yàn),記錄下來與大家分享。
首先初始化List,代碼如下:
package com.cicc.am.test;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
System.out.println(list);
}
}
輸出結(jié)果為[1, 2, 3, 3, 4]
1、普通for循環(huán)遍歷List刪除指定元素--錯(cuò)誤?。?!
for(int i=0;i<list.size();i++){
if(list.get(i)==3) list.remove(i);
}
System.out.println(list);
輸出結(jié)果:[1, 2, 3, 4]
為什么元素3只刪除了一個(gè)?本以為這代碼再簡單不過,可還是掉入了陷阱里,上面的代碼這樣寫的話,元素3是過濾不完的。只要list中有相鄰2個(gè)相同的元素,就過濾不完。List調(diào)用remove(index)方法后,會(huì)移除index位置上的元素,index之后的元素就全部依次左移,即索引依次-1要保證能操作所有的數(shù)據(jù),需要把index-1,否則原來索引為index+1的元素就無法遍歷到(因?yàn)樵瓉硭饕秊閕ndex+1的數(shù)據(jù),在執(zhí)行移除操作后,索引變成index了,如果沒有index-1的操作,就不會(huì)遍歷到該元素,而是遍歷該元素的下一個(gè)元素)。
如果這樣,刪除元素后同步調(diào)整索引或者倒序遍歷刪除元素,是否可行呢?
2、for循環(huán)遍歷List刪除元素時(shí),讓索引同步調(diào)整--正確!
for(int i=0;i<list.size();i++){
if(list.get(i)==3) list.remove(i--);
}
System.out.println(list);
輸出結(jié)果:[1, 2, 4]
3、倒序遍歷List刪除元素--正確!
for(int i=list.size()-1;i>=0;i--){
if(list.get(i)==3){
list.remove(i);
}
}
System.out.println(list);
輸出結(jié)果:[1, 2, 4]
4、foreach遍歷List刪除元素--錯(cuò)誤?。?!
for(Integer i:list){
if(i==3) list.remove(i);
}
System.out.println(list);
拋出異常:java.util.ConcurrentModificationException
foreach 寫法實(shí)際上是對的 Iterable、hasNext、next方法的簡寫。因此從List.iterator()源碼著手分析,跟蹤iterator()方法,該方法返回了 Itr 迭代器對象。
public Iterator<E> iterator() {
return new Itr();
}
Itr 類定義如下:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
通過代碼我們發(fā)現(xiàn) Itr 是 ArrayList 中定義的一個(gè)私有內(nèi)部類,在 next、remove方法中都會(huì)調(diào)用checkForComodification 方法,該方法的 作用是判斷 modCount != expectedModCount是否相等,如果不相等則拋出ConcurrentModificationException異常。每次正常執(zhí)行 remove 方法后,都會(huì)對執(zhí)行expectedModCount = modCount賦值,保證兩個(gè)值相等,那么問題基本上已經(jīng)清晰了,在 foreach 循環(huán)中
執(zhí)行 list.remove(item);,對 list 對象的 modCount 值進(jìn)行了修改,而 list 對象的迭代器的 expectedModCount 值未進(jìn)行修改,因此拋出了ConcurrentModificationException異常。
5、迭代刪除List元素--正確!
java中所有的集合對象類型都實(shí)現(xiàn)了Iterator接口,遍歷時(shí)都可以進(jìn)行迭代:
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
if(it.next()==3){
it.remove();
}
}
System.out.println(list);
輸出結(jié)果:[1, 2, 4]
Iterator.remove() 方法會(huì)在刪除當(dāng)前迭代對象的同時(shí),會(huì)保留原來元素的索引。所以用迭代刪除元素是最保險(xiǎn)的方法,建議大家使用List過程
中需要?jiǎng)h除元素時(shí),使用這種方式。
6、迭代遍歷,用list.remove(i)方法刪除元素--錯(cuò)誤?。?!
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
Integer value=it.next();
if(value==3){
list.remove(value);
}
}
System.out.println(list);
拋出異常:java.util.ConcurrentModificationException,原理同上述方法4.
7、List刪除元素時(shí),注意Integer類型和int類型的區(qū)別.
上述Integer的list,直接刪除元素2,代碼如下:
list.remove(2); System.out.println(list);
輸出結(jié)果:[1, 2, 3, 4]
可以看出,List刪除元素時(shí)傳入數(shù)字時(shí),默認(rèn)按索引刪除。如果需要?jiǎng)h除Integer對象,調(diào)用remove(object)方法,需要傳入Integer類型,代碼如下:
list.remove(new Integer(2)); System.out.println(list);
輸出結(jié)果:[1, 3, 3, 4]
總結(jié):
1、用for循環(huán)遍歷List刪除元素時(shí),需要注意索引會(huì)左移的問題。
2、List刪除元素時(shí),為避免陷阱,建議使用迭代器iterator的remove方式。
3、List刪除元素時(shí),默認(rèn)按索引刪除,而不是對象刪除。
到此這篇關(guān)于Java List的remove()方法踩坑的文章就介紹到這了,更多相關(guān)Java List remove()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
教你用Java Swing實(shí)現(xiàn)自助取款機(jī)系統(tǒng)
今天給大家?guī)淼氖顷P(guān)于JAVA的相關(guān)知識(shí),文章圍繞著如何用Java Swing實(shí)現(xiàn)自助取款機(jī)系統(tǒng)展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Java基于JNDI 實(shí)現(xiàn)讀寫分離的示例代碼
本文主要介紹了Java基于JNDI 實(shí)現(xiàn)讀寫分離的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
spring?boot前后端交互之?dāng)?shù)據(jù)格式轉(zhuǎn)換問題
這篇文章主要介紹了spring?boot前后端交互之?dāng)?shù)據(jù)格式轉(zhuǎn)換,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-01-01
關(guān)于SpringCloud整合RabbitMQ的實(shí)例
這篇文章主要介紹了關(guān)于SpringCloud整合RabbitMQ的實(shí)例,消息隊(duì)列是指利用高效可靠的消息傳遞機(jī)制進(jìn)行與平臺(tái)無關(guān)的數(shù)據(jù)交流,并基于數(shù)據(jù)通信來進(jìn)行分布式系統(tǒng)的集成,是在消息的傳輸過程中保存消息的容器,需要的朋友可以參考下2023-07-07
spring boot整合RabbitMQ(Direct模式)
springboot集成RabbitMQ非常簡單,如果只是簡單的使用配置非常少,springboot提供了spring-boot-starter-amqp項(xiàng)目對消息各種支持。下面通過本文給大家介紹下spring boot整合RabbitMQ(Direct模式),需要的朋友可以參考下2017-04-04
新建springboot項(xiàng)目時(shí),entityManagerFactory報(bào)錯(cuò)的解決
這篇文章主要介紹了新建springboot項(xiàng)目時(shí),entityManagerFactory報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
Apache Shrio安全框架實(shí)現(xiàn)原理及實(shí)例詳解
這篇文章主要介紹了Apache Shrio安全框架實(shí)現(xiàn)原理及實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04

