1

所以我有这四个类/接口:

  public class Box <S extends SomeClass> implements Comparable <Box<S>> {...}
  public interface SomeClass <T extends Comparable<T>> {...}
  public class ThisItem implements SomeClass {...}
  public class OtherItem implements SomeClass {...}

我正在尝试创建一个包含 ThisItem 实例列表的 Box 列表。我不确定为什么这会给我一个错误。

  public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>();
  this.variable.add(new ArrayList<Box<ThisItem>>(5));
4

5 回答 5

5

Box是一个泛型类,所以当它作为 使用时Box,它是一个原始类型,它不同于Box<ThisItem>具有指定类型参数的 。这类似于类型参数ArrayList<Box>Box

改变这个:

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>();

至:

public ArrayList<ArrayList<Box<ThisItem>>> variable = new ArrayList<ArrayList<Box<ThisItem>>>();
于 2013-05-10T00:20:31.803 回答
1

您如何看待,让variablestore list like安全ArrayList<Box<ThisItem>>吗?

如果 Java 允许这种情况发生,那么在从中获取该列表variable时将被转换为ArrayList<Box>. 因为返回的列表可以让您将任何类型的Box对象添加到该列表中,最初ArrayList<Box<ThisItem>>假设只存储Box<ThisItem>对象。

为了摆脱这个问题,你应该声明你variable

public ArrayList<ArrayList<Box<ThisItem>>> variable
 = new ArrayList<ArrayList<Box<ThisItem>>>();
于 2013-05-10T00:32:54.103 回答
1

ThisItem是;的原始类型 SomeClass它与将其声明为大致相同implements SomeClass<Object>,因此编译器无法验证它是否适合以这种方式使用。

而是将其声明为类型:

public class ThisItem implements SomeClass<SomeComparableClass> {...}
于 2013-05-10T00:22:31.837 回答
0

那这个呢..

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>();
this.variable.add(new ArrayList<Box<ThisItem>>(5));

至...

public ArrayList<ArrayList<Box>> variable = new ArrayList<ArrayList<Box>>();
ArrayList<Box<ThisItem>> tempInstance = new ArrayList<>();
tempInstance.add(new Box<ThisItem>()); //add new Boxes manually as you wish
this.variable.add(tempInstance);
于 2013-05-10T00:29:53.580 回答
0

这应该有效:

public ArrayList<ArrayList<? extends Box>> variable = new ArrayList<ArrayList<? extends Box>>();
于 2013-05-10T02:59:48.550 回答