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

Java初学者:使用endsWith方法时遭遇编译错误求解答

你的代码存在两个核心问题:

1. 原始类型Iterator导致编译错误

你声明的Iterator it是未指定泛型的原始类型,it.next()会返回Object类型,而Object类并没有endsWith()方法,这直接触发了编译错误。

修复方式:给Iterator指定泛型参数String,修改声明为:

Iterator<String> it = words.iterator();

这样it.next()会明确返回String类型,就能正常调用endsWith()方法。

2. 不可修改列表导致运行时异常

即便解决了编译问题,运行代码时会抛出UnsupportedOperationException——因为List.of()创建的是固定大小的不可修改列表,不支持remove()这类修改操作。

修复方式:将列表初始化为支持修改的实现,比如ArrayList:

List<String> words = new ArrayList<>(List.of("Apple", "Bat", "Cat"));

这样就能通过Iterator的remove()方法正常删除元素了。

修正后的完整代码

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("Apple", "Bat", "Cat"));

        Iterator<String> it = words.iterator();

        while (it.hasNext()) {
            if (it.next().endsWith("at")) {
                it.remove();
            }
        }

        // 验证结果
        System.out.println(words); // 输出 [Apple]
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:55:33