Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
Ashraf Mulla Avatar asked Aug 04 '26 15:08

Ashraf Mulla


1 Answers

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);
like image 167
heaprc Avatar answered Aug 07 '26 04:08

heaprc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!