如何从LinkedList<Integer>数组中删除元素?代码报错求助
Ah, I see the issue here! Let's break this down. The error happens because of Java's method overloading matching rules. LinkedList has two remove methods:
remove(int index): Deletes an element by its index positionremove(Object o): Deletes an element by its object value
When you write ar[0].remove(66), the 66 is an int primitive type. Java will prioritize matching the remove(int index) method instead of the object-based one. Since your ar[0] only has 3 elements (with indices 0, 1, 2), trying to access index 66 will throw an IndexOutOfBoundsException.
There are two solid ways to fix this:
1. Explicitly call the object-based remove method
Wrap the int value 66 into an Integer object to force Java to use the remove(Object o) overload:
// Option 1: Use Integer.valueOf() for autoboxing ar[0].remove(Integer.valueOf(66)); // Option 2: Use explicit type casting ar[0].remove((Integer) 66);
2. Find the element index first, then delete
If you want to make sure the element exists before deleting it, use indexOf to get its position first:
int targetIndex = ar[0].indexOf(66); if (targetIndex != -1) { // Check if the element exists ar[0].remove(targetIndex); }
Either of these approaches will correctly delete the element 66 from ar[0]!
内容的提问来源于stack exchange,提问作者Shivam Pandey

