Search code examples
javahashtable

Iterate over Hashtable<Integer, Object> in java


In one of my classes, I have something like this:

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

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

I use the id number as a key in the Java API HashTable and I use the object Foo as a value. In my next class, I want to print all my keys and the values, so I try

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

Now, that doesn't quite do what I want it to do. I want my values to be evenly spaced like this:

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

I can't fix it in my toString class because the values won't be evenly spaced there and also because I am using that specific representation of Foo somewhere else in my program.


Solution

  • First, make sure you can access to your Foo's members. Define a public getter on each members:

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

    Then represent it like you want into your while loop :

    while(keys.hasMoreElements()) {
        String key = keys.nextElement();
        Foo value = hashable.get(key);
    
        System.out.println(value.getId + "    "  + value.getClient + "    "  + value.getContents);
    }