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

时间:2017-01-15 18:40:27

标签: java generics arraylist collections

我有这个界面:

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

实现此接口的2个类:Passenger和CargoItem

public class Passenger implements Carriable 
public class CargoItem implements Carriable

我还有一个Class Compartment,可以是Passenger类型,也可以是CargoItem类型,不是两者都有,并且有一些carriables(passenger / 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);

1 个答案:

答案 0 :(得分:3)

只要你没有真正兴趣获得你回来的子类型,你可以改用它:

template.o: In function `main':
template.c:32: undefined reference to `__aeabi_i2f'
template.c:32: undefined reference to `__aeabi_fmul'
template.c:32: undefined reference to `__aeabi_i2f'
template.c:32: undefined reference to `__aeabi_fdiv'
template.c:33: undefined reference to `__aeabi_i2f'
template.c:33: undefined reference to `__aeabi_fmul'
template.c:33: undefined reference to `__aeabi_fadd'
template.c:33: undefined reference to `__aeabi_i2f'
template.c:33: undefined reference to `__aeabi_fdiv'