有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

集合Java ArrayList在从列表中删除项后引发IndexOutOfBoundsException

当我们创建ArrayList并检查其大小时,它给出的值为0。然而,当我们添加一个元素并删除该元素,然后检查其大小时,它抛出异常

remove()方法的内部实现是什么,它改变了空列表的定义

下面的代码将输出为0

List<Integer> list2 = new ArrayList<Integer>();
System.out.println(list2.size());

下面的代码引发异常:

List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
System.out.println(list1.size());
list1.remove(1);
System.out.println(list1.size());

共 (6) 个答案

  1. # 1 楼答案

    您的困惑是因为List#add()将传递给它的参数添加到第一个位置,即索引为零。另一方面,List#remove(int index)删除指定索引处的项。由于您指定的是索引1,因此代码失败并出现异常

    这可能是您打算做的:

    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    System.out.println(list1.size());
    list1.remove(0);
    System.out.println(list1.size());  // should print 0, with no exception
    
  2. # 2 楼答案

    remove(int index)
    

    索引,而不是值

  3. # 3 楼答案

    你的逻辑有问题

    List<Integer> list1 = new ArrayList<Integer>();
    list1.add(1);
    System.out.println(list1.size());
    list1.remove(1);
    System.out.println(list1.size());
    

    将整数值添加到列表中。所以它把大小打印为1。但随后您从列表中删除了该值。当您从列表中删除某些内容时,可以使用int index调用remove(),这是一种方法。因此,必须插入相关值的索引,而不是值。然后您可以看到没有属于索引编号1的值。仅存在索引号0。因此,它将抛出一个数组索引超出绑定异常。有关详细信息,请参见^a1}

  4. # 4 楼答案

    清单1。删除(1)

    您正在尝试从索引1中删除元素,而不是从值1中删除。因此,数组索引超出了界限错误

  5. # 5 楼答案

    List中有两个remove方法。有^{}^{}

    如果调用remove(1),它将解析为remove(int index),并尝试删除列表中索引1处的项(超出范围)

    如果要从列表中删除对象1,请通过调用

    remove((Integer) 1)
    

    由于Integer是一个对象,因此将调用remove(Object)

  6. # 6 楼答案

    list1.add(1); 将向arraylist列表1添加1,但在

    list1.remove(1);
    

    将删除数组列表的索引1(第二个位置,因为ArrayList索引从0开始)中的值

    成功

    list1.remove(0)
    

    而且会起作用