在 java 中迭代 Hashtable<Integer, Object>

Iterate over Hashtable<Integer, Object> in java

在我的一个 classes 中,我有这样的东西:

public Foo(int id, String client, String contents) {
    this.id = id;
    this.client = client;
    this.contents = contents;
}

public String toString() {
    return id + contents + client;
}

我使用 ID 号作为 Java API 哈希表中的键,我使用对象 Foo 作为值。 在我的下一个 class 中,我想打印我所有的键和值,所以我尝试

Hashtable<Integer, Object> hashtable = new Hashtable<>();
Enumeration<Integer> keys = hashtable.keys();
Collection<Object> values = hashtable.values();
while(keys.hasMoreElements() ){
    System.out.printf("%-5d%-5s", keys.nextElement(), values.toString());
}

现在,这并不能完全满足我的要求。我希望我的值像这样均匀分布:

ID #1        ID #1          client #1          content #1
ID #2        ID #2          client #2          content #2
ID #3        ID #3          client #3          content #3

我无法在我的 toString class 中修复它,因为那里的值不会均匀分布,也因为我在程序的其他地方使用了 Foo 的特定表示。

首先,确保您可以访问 Foo 的成员。在每个成员上定义一个 public getter:

public Foo(int id, String client, String contents) {
    this.id = id;
    this.client = client;
    this.contents = contents;
}

public int getId() {
    return this.id;
}

public String getClient() {
    return this.client;
}

public String getContents() {
    return this.contents;
}

然后在 while 循环中按照您想要的方式表示它:

while(keys.hasMoreElements()) {
    String key = keys.nextElement();
    Foo value = hashable.get(key);

    System.out.println(value.getId + "    "  + value.getClient + "    "  + value.getContents);
}