本文介绍了多个嵌套通配符 - 参数不适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
>








另请参阅





    • | |









I've heavily simplified my problem. Here's how it reads.

I'm trying to figure out why the following code does not compile:

 List<AnonType<AnonType<?>>> l = new ArrayList<AnonType<AnonType<?>>>();
 l.add( new AnonType<AnonType<String>>() );

where

public class AnonType<T> {
  T a;

  List<T> b;
}

The compiler error is saying that add is not applicable for the argument given. OTOH, the following code with only 1-level nested wildcard compiles perfectly:

List<AnonType<?>> l = new ArrayList<AnonType<?>>();
l.add( new AnonType<String>() );
解决方案

The following compiles as expected:

    List<Set<? extends Set<?>>> list = new ArrayList<Set<? extends Set<?>>>();
    list.add(new HashSet<Set<String>>());
    list.add(new HashSet<Set<Integer>>());

The problem is that generics is type invariant.

Consider the simpler example:

  • Given that there is a casting conversion from Animal to Dog (e.g. Dog extends Animal)...
    • A List<Animal> IS NOT a List<Dog>
  • There is a capture conversion from List<? extends Animal> to a List<Dog>

Now here's what happens in this scenario:

  • Given that there is a capture conversion from Set<?> to Set<String>...
    • A Set<Set<?>> IS NOT a Set<Set<String>>
  • There is a capture conversion from Set<? extends Set<?>> to Set<Set<String>>

So if you want a List<T> where you can add a Set<Set<String>>, Set<Set<Integer>>, etc, then T is NOT Set<Set<?>>, but rather Set<? extends Set<?>>.

Related questionsSee also

这篇关于多个嵌套通配符 - 参数不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:16