我有这个界面:
public interface Carriable
{
public abstract String getName();
}
以及实现此接口(interface)的 2 个类:Passenger 和 CargoItem
public class Passenger implements Carriable
public class CargoItem implements Carriable
我还有一个类 Compartment,它可以是 Passenger 类型或 CargoItem 类型,但不能同时是 CargoItem 类型,并且有一些 carriables(passengers/cargoItems)
public class Compartment<T extends Carriable>
{
...
private ArrayList<T> allCarriables;
...
}
所有这些都在问题声明中明确说明。 现在我想创建一个具有“一些独特的链接隔间”的 Ship 类。我想写
public class Ship
{
private Set<Compartment<T extends Carriable>> allComaprtments;
}
为了能够添加 2 种不同类型的隔间。为什么不允许这样做?另一种方法是什么?
更新:
我希望能够添加特定类型的隔间,例如:
Compartment<Passenger> oneComp= new Compartment();
this.allComaprtments.add(oneComp);
最佳答案
只要您对获取返回的子类型没有真正的兴趣,就可以改用它:
public class Ship
{
private Set<Compartment<? extends Carriable>> allComaprtments;
}
关于java - 通用类型元素的 ArrayList - 可以做到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41664830/