如何打印 <Object, Integer> 的 LinkedHashMap?

How can I print a LinkedHashMap of <Object, Integer>?

所以我有一个带有一些私有变量的 class 宇宙飞船,其中一个有另一个 Class 的 LinkedHashMap 和一个像这样的 Integer

private LinkedHashMap<Resource, Integer> cargo;

Resource 是一个抽象 class,它有多种类型的资源(如 ResourceBlue、ResourceRed 等...)

我可以用抽象 class 做一个 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。

在完成初始化语句之前,您不能将对象放入货物中。 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) ,但是您需要 @Override 每个 [=14] 的 toString() 方法=] 对象。否则,默认情况下,对它们调用 toString() 将只打印 class 名称和内存引用。

如果您想使用这种初始化方式,请不要在所有 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);
    }
};

你用那个 shorthand 做的事情实际上相当复杂。您正在创建 anonymous subclass of LinkedHashMap containing a non-static block。该非静态块类似于构造函数,在对象实例化期间将是 运行。因为您的对象尚未实例化,所以您的 "cargo" 变量将不存在。在非静态块中,类似于构造函数,您可以使用 "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);
    }
};

另外,因为你的 cargo LinkedHashMap 刚刚被创建,所以它会是空的。所以你可以将 "putIfAbsent" 简化为 "put".