简体   繁体   English

如何在 Java 中将泛型列表作为参数传递,并为该列表定义子类型作为值?

[英]How do I pass a generic List as parameter in Java with a defined subtype for that list as value?

I am trying to use generics to create some flexible data handling, but I am stumbling across a compiler error which I don't know how to get around.我正在尝试使用泛型来创建一些灵活的数据处理,但是我偶然发现了一个我不知道如何解决的编译器错误。 Example code:示例代码:

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

public class Spielwiese {
    
    class A {
        public A() { }
    }
    
    class B extends A {
        public B() { }
    }
    
    class C<T extends A> {
        T value = null;
        public C() {}
        public void setValue(T v) {
            value = v;
        }
    }

    public static void doSomething(List<C<? extends A>> stuff) { }
    
    public static void main(String[] argv) {
        List<C<B>> stuff = new ArrayList<>(); 
        doSomething(stuff); // compiler error: "The method doSomething(List<C<? extends A>> stuff) is not applicable for the arguments (List<C<B>>)"
    }
}

Why doesn't this work, even though B extends A as required?即使 B 根据需要扩展了 A,为什么这不起作用?

@Sweeper posted the solution: @Sweeper 发布了解决方案:

public static void doSomething(List<? extends C<? extends A>> stuff) { }

This allows to pass a List<C<B>> as a parameter just nicely.这允许将List<C<B>>作为参数很好地传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM