我如何打印?的LinkedHashMap。

问题描述 投票:0回答:2
所以我有一个带有一些私有变量的宇宙飞船类,其中一个具有另一个类的LinkedHashMap和一个这样的整数

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

资源是...

java constructor nullpointerexception linkedhashmap
2个回答
1
投票
在完成初始化语句之前,您不能将物品放入货物中。putIfAbsent()调用应在以下位置进行:

0
投票
如果要使用这种初始化样式,请不要在所有cargo.调用之前都写putIfAbsent()cargo此时仍为空。
© www.soinside.com 2019 - 2024. All rights reserved.