Java泛型类找不到方法
对于我的CS分配,我需要编写一个实现container接口的通用Bag对象。袋子应该只能容纳实现Thing接口的物品。我的问题是,当我试图编译时,我得到了这个
Bag.java:23: error: cannot find symbol
if (thing.getMass() + weight >= maxWeight) {
symbol: method getMass()
location: variable thing of type Thing
where thing is a type-variable:
Thing extends Object declared in class Bag
getMass()方法在Thing接口中有明确定义,但我无法让Bag对象找到它。这是我的班级档案
public interface Thing {
public double getMass();
}
public class Bag<Thing> implements Container<Thing> {
private ArrayList<Thing> things = new ArrayList<Thing>();
private double maxWeight = 0.0;
private double weight = 0.0;
public void create(double maxCapacity) {
maxWeight = maxCapacity;
}
public void insert(Thing thing) throws OutOfSpaceException {
if (thing.getMass() + weight >= maxWeight) {
things.add(thing);
weight += thing.getMass();
} else {
throw new OutOfSpaceException();
}
}
}
public interface Container<E> {
public void create(double maxCapacity);
public void insert(E thing) throws OutOfSpaceException;
public E remove() throws EmptyContainerException;
public double getMass();
public double getRemainingCapacity();
public String toString();
}
我发布了所有我认为与节省空间相关的代码。如果问题很难找到,我可以发布每一行。请告诉我
# 1 楼答案
还有一个额外的
<Thing>
让编译器感到困惑。改变到
现在,您正在创建一个名为
Thing
的新类型变量,该变量隐藏了现有的Thing
接口。你现在写的相当于。。。只需要一个名为
Thing
而不是E
的变量