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

从ArrayList移除奇数元素时List<Integer>报错的技术咨询

Fixing the Compilation Error in Your Odd Number Removal Method

Hey there! Let's break down why you're seeing that error and how to fix it quickly.

The Root Cause of the Error

Your method removeOddNumbers is declared to return a List<Integer> (the parent interface), but in your test code, you're trying to assign that return value directly to an ArrayList<Integer> variable:

ArrayList<Integer> result = removeOddNumbers(arrayList);

Java doesn't allow this because a parent type reference can't be implicitly converted to a child type—even though your method actually returns the input ArrayList, the compiler only checks the method's declared return type, not the actual runtime value.

Solutions to Fix the Error

You have three solid options to resolve this, depending on your needs:

  1. Use the parent interface type for the result variable (Recommended)
    This follows Java's "program to an interface" best practice, making your code more flexible if you ever switch to a different List implementation later:

    List<Integer> result = removeOddNumbers(arrayList);
    
  2. Explicitly cast the return value to ArrayList
    If you absolutely need an ArrayList type variable, you can add a cast. Just note that this will throw a ClassCastException if the method ever returns a non-ArrayList List in the future:

    ArrayList<Integer> result = (ArrayList<Integer>) removeOddNumbers(arrayList);
    
  3. Change the method's return type to ArrayList
    This makes the return type match the concrete class you're returning, but it reduces the method's flexibility (you can't return other List implementations like LinkedList without changing the signature):

    public static ArrayList<Integer> removeOddNumbers(ArrayList<Integer> list) {
        if (list.isEmpty()) { throw new IllegalStateException("List cannot be empty"); }
        List<Integer> toRemove = new ArrayList<>();
    
        for (int i : list) {
            if (i % 2 != 0) { toRemove.add(i); }
        }
        list.removeAll(toRemove);
        return list;
    }
    

A Quick Side Note

Instead of throwing an Error when the list is empty, consider using a standard runtime exception like IllegalStateException or IllegalArgumentException. Error is reserved for serious JVM-level issues (like out-of-memory errors), not application-level validation failures.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:09:07