您的位置:首页技术文章
文章详情页

浅谈Java list.remove( )方法需要注意的两个坑

【字号: 日期:2022-08-20 09:12:14浏览:9作者:猪猪

list.remove

最近做项目的过程中,需要用到list.remove()方法,结果发现两个有趣的坑,经过分析后找到原因,记录一下跟大家分享一下。

代码

直接上一段代码,进行分析。

public class Main { public static void main(String[] args) { List<String> stringList = new ArrayList<>();//数据集合 List<Integer> integerList = new ArrayList<>();//存储remove的位置 stringList.add('a'); stringList.add('b'); stringList.add('c'); stringList.add('d'); stringList.add('e'); integerList.add(2); integerList.add(4);//此处相当于要移除最后一个数据 for (Integer i :integerList){ stringList.remove(i); } for (String s :stringList){ System.out.println(s); } }}

如上代码我们有一个5个元素的list数据集合,我们要删除第2个和第4个位置的数据。

第一次运行

浅谈Java list.remove( )方法需要注意的两个坑

咦,为什么执行两次remove(),stringList的数据没有变化呢?

没有报错,说明代码没有问题,那问题出在哪呢?

仔细分析我们发现,remove()这个方法是一个重载方法,即remove(int position)和remove(object object),唯一的区别是参数类型。

for (Integer i :integerList){ stringList.remove(i); }

仔细观察上面代码你会发现,其实i是Integer对象,而由于Java系统中如果找不到准确的对象,会自动向上升级,而(int < Integer < Object),所以在调用stringList.remove(i)时,其实使用的remove(object object),而很明显stringList不存在Integer对象,自然会移除失败(0.0),Java也不会因此报错。

如果我们想使用remove(int position)方法,只能降低对象等级,即修改代码;

for (Integer i :integerList){ int a =i; stringList.remove(a); }

第二次运行

浅谈Java list.remove( )方法需要注意的两个坑

我们发现提示在坐标为4的地方越界了,这是为什么呢?

其实很简单,因为执行stringList.remove(2)后,list.size()就-1为4了,我们原来要移除的最后一个位置的数据移动到了第3个位置上,自然就造成了越界。

我们修改代码先执行stringList.remove(4),再执行执行stringList.remove(2)。

integerList.add(4);

integerList.add(2);

这个错误提醒我们:使用remove()的方法时,要先从大到小的位置移除。当然如果你知道具体的对象,直接移除remove(对象)更稳妥。

第三次执行

浅谈Java list.remove( )方法需要注意的两个坑

嗯,这次没问题了。

总结

1、使用remove()的方法时,要先从大到小的位置移除。当然如果你知道具体的对象,直接移除remove(对象)更稳妥。

2、要密切注意自己调用的remove()方法中的,传入的是int类型还是一个对象。

补充知识: 关于List.remove()报错的问题

我们如果想删掉List中某一个对象,我们可能就会想到会用List.remove()方法。但是这样如果后续操作这个list的时候就会报错。

具体的原因是当你操作了List的remove方法的时候,他回去修改List的modCount属性。

导致抛出异常java.util.ConcurrentModificationException。

最好的想要修改List对象,我们可以用ListIterator。

就像这样:

ArrayList<Integer> arrayList = new ArrayList<>(); for (int i = 0; i < 20; i++) { arrayList.add(Integer.valueOf(i)); }ListIterator<Integer> iterator = arrayList.listIterator();while (iterator.hasNext()) {if(需要满足的条件){iterator.remove();//删除操作iterator.add(integer);//新增操作}}

这样就不会去修改List的modCount属性。

以上这篇浅谈Java list.remove( )方法需要注意的两个坑就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Java
相关文章: