有 Java 编程相关的问题?

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

java使用remove(对象)从LinkedList中删除整数

我想使用items值从Integer LinkedList中删除一个项目。但我却得到了ArrayIndexOutOfBoundException

public static void main(String[] args) {

    List<Integer> list = new LinkedList<Integer>();
    list.add(10);
    list.add(20);
    list.add(5);

    list.remove(10);
    System.out.println("Size: " + list.size());

    for (Integer integer : list) {
        System.out.println(integer);
    }
}

我期望的输出是一个只有2个元素20和5的列表。但我得到了以下例外:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 3
at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
at java.base/java.util.LinkedList.remove(LinkedList.java:529)
at Collections.LinkedListTest.main(LinkedListTest.java:15)

LinkedList将我传递的数字视为索引,而不是值。那么,我如何在不使用索引号的情况下将项目10作为一个值删除呢


共 (2) 个答案

  1. # 1 楼答案

    您应该使用接受整数对象的版本:

    list.remove(Integer.valueOf(10)));
    

    ,而不是将索引作为int数据类型的remove版本:

    list.remove(10);
    
  2. # 2 楼答案

    如果查看LinkedList docsremove,则需要索引、要删除的对象或对象本身,或者不需要参数

    remove() Retrieves and removes the head (first element) of this list.

    remove(int index) Removes the element at the specified position in this list.

    remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.

    在您的情况下,如果传递int,它将使用该方法删除该索引处的对象,并且它应为0,因为它是第一个元素:

    public static void main(String[] args) {
    
        List<Integer> list = new LinkedList<Integer>();
        list.add(10);
        list.add(20);
        list.add(5);
    
        list.remove(0);
        System.out.println("Size: " + list.size());
    
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
    

    如果你想删除一个值,你应该传递一个对象(在本例中是Integer),而不是int primitive