对于我的CS分配,我需要编写一个实现容器接口的通用Bag对象。 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();
}
我发布了我认为与节省空间相关的所有代码。如果问题很难找到,我可以发布每一行。请告诉我。
答案 0 :(得分:8)
还有一个额外的<Thing>
让编译器感到困惑。变化
public class Bag<Thing> implements Container<Thing> {
到
public class Bag implements Container<Thing> {
现在,您正在创建名为Thing
的新类型变量,隐藏现有的Thing
界面。你现在写的东西相当于
public class Bag<E> implements Container<E>
...只是使用名为Thing
而非E
的变量。