Java的泛型类型和接口

Java的泛型类型和接口,java,generics,interface,Java,Generics,Interface,拥有这些类和接口 public interface Shape; public interface Line extends Shape public interface ShapeCollection< Shape> public class MyClass implements ShapeCollection< Line> List< ShapeCollection< Shape>> shapeCollections = new Lin

拥有这些类和接口

public interface Shape;

public interface Line extends Shape

public interface ShapeCollection< Shape>

public class MyClass implements ShapeCollection< Line>

List< ShapeCollection< Shape>> shapeCollections = new LinkedList< ShapeCollection< Shape>>();
公共界面形状;
公共接口线延伸形状
公共接口ShapeCollection
公共类MyClass实现ShapeCollection
List>shapeCollections=newlinkedlist>();

当我尝试将
MyClass
的一个实例添加到
shapeCollections
时,Eclipse仍然要求
MyClass
实现
ShapeCollection
,因为它实现了
ShapeCollection
Shape
的扩展。我尝试更改为
ShapeCollection
,但没有结果。任何帮助都将不胜感激。

根据您的声明
MyClass
不实现
ShapeCollection
。即使有,也没关系。您只能放置扩展
Shape
的对象,而不能放置扩展
ShapeCollection

的对象。您已声明了名为
Shape
Line
等的类型参数。您尚未声明绑定。也就是说,这两个声明是相同的:

public interface ShapeCollection<Shape> // generic parameter called Shape
public interface ShapeCollection<T>  // generic parameter called T

这是因为
集合
不是
集合
的子类:泛型与类层次结构不同。

形状
的子类型并不意味着
形状集合
形状集合
的子类型。我相信您将需要类似于
list的东西,但例如,实现ShapeCollection的MyClass允许我实现其方法,因为它接受线条作为形状。我已经试过了,但还是非常感谢。是的,成功了,非常感谢。我认为直线是形状的延伸,这是可以接受的。那么写作呢?扩展Shape基本上说它接受任何扩展Shape?集合的内容
public interface ShapeCollection<T extends Shape> // generic parameter bound to Shape
List<ShapeCollection<? extends Shape>> shapeCollections = new LinkedList<ShapeCollection<? extends Shape>>();
shapeCollections.add(new MyClass()); // should work