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

Java泛型extends/super疑问:不可添加元素的List场景及代码差异

Understanding Bounded Wildcards in Java Lists

Scenarios for List<? extends Number> (Cannot Add Elements)

You’re right that returning this type from a method is a common use case—it lets you expose a read-only view of a specific subclass list (like ArrayList<Integer>) while retaining the flexibility of treating it as a collection of Numbers. But there are other practical scenarios too:

1. Read-Only Method Parameters

Use this wildcard when you need a method that only reads from a collection, regardless of the specific Number subclass it holds. This makes your method far more flexible than using List<Number>, since you can pass in ArrayList<Integer>, LinkedList<Double>, etc.—types that aren’t compatible with List<Number> directly.

Example:

public static double calculateTotal(List<? extends Number> numbers) {
    double total = 0.0;
    for (Number num : numbers) {
        total += num.doubleValue();
    }
    return total;
}

You can call this with calculateTotal(new ArrayList<Integer>()) or calculateTotal(new ArrayList<Double>())—both work perfectly, since we only need to access Number-level methods.

2. Immutable Collection Holders

If you have a class that needs to store a collection of Number subclasses but should never modify it (only read), declaring the member variable as List<? extends Number> enforces this at compile time. It blocks accidental calls to add() or other mutation methods, keeping your internal state safe.

3. Compatibility with Generic APIs

Many generic utility libraries use bounded wildcards to accept a range of collection types. For example, if you’re working with a data processing tool that handles numeric datasets, using List<? extends Number> lets you integrate with different numeric collections without messy casting.


Differences Between List<? super Number> and List<Number>

Let’s break down the key distinctions between your two code snippets:

1. Element Retrieval Type

  • List<Number>: When you call get(), you get a Number directly. You can immediately use all Number methods (like doubleValue(), intValue()) without casting:
    Number num = myList.get(0);
    double val = num.doubleValue(); // No casting needed
    
  • List<? super Number>: The compiler only knows elements are a supertype of Number (could be Number, Serializable, or even Object). So get() returns an Object, and you need to cast to Number to use its methods:
    Object obj = myList.get(0);
    if (obj instanceof Number) {
        double val = ((Number) obj).doubleValue(); // Cast required
    }
    

2. Assignment Flexibility

  • List<Number>: Can only be assigned to collections explicitly typed as List<Number> (or its concrete subclasses like ArrayList<Number>). You can’t assign a List<Object> or List<Serializable> to it—those are incompatible:
    // Compile error!
    // List<Number> myList = new ArrayList<Object>();
    
  • List<? super Number>: Can accept any collection whose type is a supertype of Number (including Object, Serializable, or Number itself):
    // All valid
    List<? super Number> list1 = new ArrayList<Object>();
    List<? super Number> list2 = new ArrayList<Serializable>();
    List<? super Number> list3 = new ArrayList<Number>();
    

3. Use Case Intent

  • List<Number>: Use this when you need to both read from and write to the collection, and you want to work directly with Number types. It makes clear that the collection is meant to hold any Number subclass, and you’ll interact with them as Numbers.
  • List<? super Number>: This follows the PECS principle (Producer Extends, Consumer Super)—use it when your code is a "consumer" that adds elements to the collection. It lets you accept a wider range of collection types, which is useful if you need to pass the collection to code that expects a more general type (like List<Object>).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:27:34