简体   繁体   中英

Removing Integer from LinkedList using remove(Object)

I want to remove an item from Integer LinkedList using the items value. But Instead I am getting the 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);
    }
}

The output I am expecting is a List with only 2 elements 20 and 5. But I am getting the below Exception:

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)

The LinkedList is treating the number I am passing as an Index instead of value. So How can I remove the item 10 as a value without using its index number.

You should use the version that takes an object of integer:

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

, not the version remove that takes an index as int datatype:

list.remove(10);

If you look at LinkedList docs remove expects the index, the object to remove or the object itself or no parameter.

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.

In your case if you pass an int it uses the method to delete the object at that index and it should be 0 as it's the first element:

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);
    }
}

If you want to delete a value you should pass an object ( Integer in this case), not the int primitive .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM