You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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 position
  • remove(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:21:37