private LinkedHashMap<Resource, Integer> cargo;
资源是一个抽象类,具有几种类型的资源(例如ResourceBlue,ResourceRed等)
我可以使用抽象类来做LinkedHashMap吗,如果可以,我该怎么做?
这是我到目前为止所拥有的:
构造函数:
public SpaceShip() {
this.cargoHold = 0;
this.upgradeLevel = 0;
this.drone = null;
this.artifact = 0;
this.crewMembers = new ArrayList<String>() {
{
add("Captain");
add("Navigation");
add("Landing");
add("Shields");
add("Cargo");
}
};
this.cargo = new LinkedHashMap<Resource, Integer>(){
{
cargo.putIfAbsent(new ResourceAzul(), 0);
cargo.putIfAbsent(new ResourcePreto(), 0);
cargo.putIfAbsent(new ResourceVerde(), 0);
cargo.putIfAbsent(new ResourceVermelho(), 0);
}
};
}
当我在主程序中运行此程序(作为测试):
SpaceShip ss = new SpaceShip();
System.out.println(ss);
这只是在构造函数的第一个“ putIfAbsent”处给我一个NullPointerException。
所以我有一个带有一些私有变量的宇宙飞船类,其中一个具有另一个类的LinkedHashMap和一个像这样的私有LinkedHashMap
资源是...
cargo.
调用之前都写putIfAbsent()
。 cargo
此时仍为空。