小编Roe*_*oel的帖子

How can I use a generic class with wildcard declaration?

I have the following member in my class:

List<? extends SomeObject> list;
Run Code Online (Sandbox Code Playgroud)

When I try to do:

list.add(list.get(0));
Run Code Online (Sandbox Code Playgroud)

I get:

Test.java:7: error: no suitable method found for add(CAP#1)
        list.add(list.get(0));
            ^
    method Collection.add(CAP#2) is not applicable
      (argument mismatch; Object cannot be converted to CAP#2)
    method List.add(CAP#2) is not applicable
      (argument mismatch; Object cannot be converted to CAP#2)
  where CAP#1,CAP#2 are fresh type-variables:
    CAP#1 extends Object from capture of ? extends Object
    CAP#2 extends Object from capture of ? extends Object
Run Code Online (Sandbox Code Playgroud)

My …

java generics wildcard

7
推荐指数
1
解决办法
100
查看次数

标签 统计

generics ×1

java ×1

wildcard ×1