繁体   English   中英

如何打印 LinkedHashMap<object, integer> ?</object,>

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

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

private LinkedHashMap<Resource, Integer> cargo;

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

我可以用抽象的 class 做一个 LinkedHashMap 吗?如果可以,我将如何做 go 呢?

这是我到目前为止所拥有的:

构造函数:

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。

你用那个速记做的实际上是相当复杂的。 您正在创建一个包含非静态 block的 LinkedHashMap 的匿名子类 该非静态块,类似于构造函数,将在对象实例化期间运行。 因为您的 object 尚未实例化,所以您的“货物”变量将不存在。 在非静态块中,与构造函数类似,您可以使用“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对象@Override toString()方法。 否则,默认情况下,对它们调用toString()只会打印 class 名称和 memory 参考。

如果你想使用这种初始化风格,就不要写cargo. 在所有putIfAbsent()调用之前。 此时cargo仍为 null。

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()的方式相匹配。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM