简体   繁体   English

通用类型的元素的ArrayList-可以完成吗?

[英]ArrayList of elements that are of a generic type - can be done?

I have this interface: 我有这个界面:

public interface Carriable
{
    public abstract String getName();
}

And the 2 classes that implement this interface : Passenger and CargoItem 以及实现此接口的2个类:Passenger和CargoItem

public class Passenger implements Carriable 
public class CargoItem implements Carriable

I also have a class Compartment that can be either of type Passenger or type CargoItem, not both and has some carriables(passengers/cargoItems) 我也有一个舱室,舱室类型可以是旅客类型,也可以是类型CargoItem,不能两者都选,并且有一些可携带物品(passengers / cargoItems)

public class Compartment<T extends Carriable>
{
    ...    
    private ArrayList<T> allCarriables;
    ...
}

All these are specifies clearly in the problem statemnet. 所有这些都在问题statemnet中明确指定。 Now I want to create a Ship class that has "some unique linked compartment". 现在,我想创建一个具有“某些唯一的链接隔间”的Ship类。 I would want to write 我想写

public class Ship
{
 private Set<Compartment<T extends Carriable>> allComaprtments;
}

in order to be able to add compartments of 2 different types. 为了能够添加2种不同类型的隔层。 Why is it not allowed and what would be another approach? 为什么不允许这样做?另一种方法是什么?

UPDATE : 更新:
I want to be able to add compartments of a specific type, for example: 我希望能够添加特定类型的隔离专区,例如:

Compartment<Passenger> oneComp= new Compartment();  

this.allComaprtments.add(oneComp);

So long as you have no real interest in getting the subtypes you get back, you can use this instead: 只要您对获取返回的子类型没有真正的兴趣,可以使用以下方法代替:

public class Ship
{
 private Set<Compartment<? extends Carriable>> allComaprtments;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM