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

如何从ArrayList中移除元素?代码报错:contains()方法参数缺失

修复ArrayList移除指定元素的代码错误

报错翻译

原报错The method contains(Object) in the type ArrayList is not applicable for the arguments ()翻译为:ArrayList的contains(Object)方法不支持无参数调用。

核心问题与修复步骤

1. 直接报错原因

你调用copy.contains()时没有传入参数,contains()方法必须接收一个待检查的对象,用来判断列表中是否存在该元素。

2. 遍历逻辑错误

同时使用普通for循环和ListIterator遍历列表,当执行listIterator.remove()后,列表的size会动态减少,导致for循环的索引j与迭代器的遍历位置不同步,最终出现遍历遗漏或NoSuchElementException。

3. 列表复制冗余

手动循环逐个添加元素的写法可以简化,直接通过ArrayList的拷贝构造方法完成列表复制:ArrayList<Rolling> copy = new ArrayList<>(sequence);。

4. Rolling类的相等性判断问题

如果Rolling类没有重写equals()和hashCode()方法,contains()或直接对象比较会基于内存引用判断,而非对象的实际值。即使两个Rolling对象的数值都是n,也会被判定为不同对象,无法正确移除目标元素。

修复后的完整代码

import java.util.ArrayList;
import java.util.ListIterator;

class Rolling {
    private int value;

    public Rolling(int value) {
        this.value = value;
    }

    // 重写equals和hashCode,确保基于value判断对象相等
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Rolling rolling = (Rolling) o;
        return value == rolling.value;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    public int getValue() {
        return value;
    }
}

public class RollingHandler {
    // 模拟生成Rolling列表的方法
    public static ArrayList<Rolling> sequenceOfDice(int count) {
        ArrayList<Rolling> sequence = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            sequence.add(new Rolling(i));
        }
        return sequence;
    }

    public static ArrayList<Rolling> remove(ArrayList<Rolling> sequence, int n) {
        // 拷贝原列表
        ArrayList<Rolling> copy = new ArrayList<>(sequence);

        // 使用ListIterator安全遍历并移除元素
        ListIterator<Rolling> iterator = copy.listIterator();
        while (iterator.hasNext()) {
            Rolling current = iterator.next();
            // 两种判断方式选其一即可
            // 方式1:利用重写的equals判断
            if (current.equals(new Rolling(n))) {
                iterator.remove();
            }
            // 方式2:直接比较属性(更高效)
            // if (current.getValue() == n) {
            //     iterator.remove();
            // }
        }

        return copy;
    }

    public static void main(String[] args) {
        ArrayList<Rolling> result = remove(sequenceOfDice(4), 4);
        // 输出验证结果
        result.forEach(r -> System.out.println(r.getValue()));
    }
}

关键说明

  • 使用while(iterator.hasNext())遍历是安全修改列表的正确方式,迭代器会自动处理元素移除后的索引变化
  • 重写equals()和hashCode()是自定义对象在集合中进行相等性判断的必要操作
  • 直接比较对象属性的方式比调用contains()更高效,避免额外的列表遍历

内容的提问来源于stack exchange,提问作者First_1st

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:26:17