如何打印<对象,整数>的链接哈希图?



所以我有一个类Spaceship,它有一些私有变量,其中一个有另一个类的LinkedHashMap和一个像这样的Integer

private LinkedHashMap<Resource, Integer> cargo;

Resource是一个抽象类,它有几种类型的资源(如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的匿名子类。该非静态块类似于构造函数,将在对象实例化期间运行。因为您的对象尚未实例化,所以您的"货物"变量将不存在。在非静态块中,类似于构造函数,可以使用"this"关键字。

this.cargo = new LinkedHashMap<Resource, Integer>(){
{
this.put(new ResourceAzul(), 0);
this.put(new ResourcePreto(), 0);
this.put(new ResourceVerde(), 0);
this.put(new ResourceVermelho(), 0);
}
};

此外,因为您的货物LinkedHashMap刚刚创建,它将是空的。因此,您可以将"putIfAbsent"简化为"put"。

在完成初始化语句之前,不能将对象放入货物中。putIfAbsent((调用应该在以下时间之后:

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);

你的实际问题中有多个问题。要回答如何打印LinkedHashMap的内容的问题,您可以将其正常打印到System.out.println(this.cargo),但您需要为每个Resource对象@OverridetoString()方法。否则,在默认情况下,对它们调用toString()将只打印类名和内存引用。

如果要使用这种类型的初始化,请不要在所有putIfAbsent()调用之前写入cargo.。此时cargo仍然为空。

this.cargo = new LinkedHashMap<Resource, Integer>(){
{
putIfAbsent(new ResourceAzul(), 0);
putIfAbsent(new ResourcePreto(), 0);
putIfAbsent(new ResourceVerde(), 0);
putIfAbsent(new ResourceVermelho(), 0);
}
};

这与您刚才写add()而不是上面写crewMembers.add()的方式相匹配。

此外,由于这是一个全新的地图,所以只调用put()会更简单。你知道地图一开始是空的,不需要putIfAbsent()

this.cargo = new LinkedHashMap<Resource, Integer>(){
{
put(new ResourceAzul(), 0);
put(new ResourcePreto(), 0);
put(new ResourceVerde(), 0);
put(new ResourceVermelho(), 0);
}
};

最新更新