Java list.remove( )方法需要注意的两个坑,才知道为啥一直不对

原文链接:https://blog.csdn.net/demonliuhui/article/details/75057512

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);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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

第一次运行

这里写图片描述

我们发现提示在坐标为4的地方越界了,这是为什么呢? 
其实很简单,因为执行stringList.remove(2)后,list.size()就-1为4了,我们原来要移除的最后一个位置的数据移动到了第3个位置上,自然就造成了越界。

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

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

第二次运行

这里写图片描述

嗯,没有报错。但是,咦,为什么执行两次remove(),stringList的数据没有变化呢? 
没有报错,说明代码没有问题,那问题出在哪呢? 
仔细分析我们发现,remove()这个方法是一个重载方法,即remove(int position)和remove(object object),唯一的区别是参数类型。


        for (Integer i :integerList){
            stringList.remove(i);
        }
  • 1
  • 2
  • 3
  • 4

仔细观察上面代码你会发现,其实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);
        }
  • 1
  • 2
  • 3
  • 4

第三次执行

这里写图片描述 
嗯,这次没问题了。

总结

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

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


猜你喜欢

转载自blog.csdn.net/weixin_30363263/article/details/80197557