Solved

Get both key and value from Hashtable element.

Posted on 2002-05-07
9
372 Views
Last Modified: 2010-03-31
I've got a Hashtable storing parameter data in a class I'm using for message passing. The key values used to index the hashtable will vary from instance to instance, as different messages will use different parameters (think of it like xml if that helps: <tag key="value" key="value">, where both the keys and values vary from tag to tag).

I need to iterate over the hashtable, extracting both the value *and* the key of each element contained therein.

The generic Iterator's next() method returns an object, which in the case of Hashtable I presume is the value section of the particlar element. The Object class contains a method int hashCode(), which seems to be something near what I'm after, except that an integer isn't of much use to me --  I need something I can extract a String key from.

How can I do this?
0
Comment
Question by:Subhuman
  • 4
  • 3
  • 2
9 Comments
 
LVL 9

Expert Comment

by:doronb
ID: 6993321
Hi,


Try this example:

     public static void iterateTable(Hashtable h) {
          if (h != null) {
               Iterator i = h.entrySet().iterator();
               while (i.hasNext()) {
                    Map.Entry me = (Map.Entry)i.next(); // Casting to Map.Entry is VERY IMPORTANT!!
                    Object key = me.getKey(); // The Key...
                    Object value = me.getValue(); // The Value..
                    // Now do something with the {key, value} pair...
               }
          }
     }

Do not forget to cast the key and value objects to whatever it is you need. I hope this helps..


Doron
0
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 6993334
Hashtable ht = .....;

Enumeration i = ht.keys();
while (i.hasMoreElements())
{
   Object key = i.nextElement();
   Object value = ht.get(key);

   // Do what you want with your key and value
}
0
 
LVL 1

Author Comment

by:Subhuman
ID: 6993408
I like object's solution more; it's much cleaner.
0
 
LVL 1

Author Comment

by:Subhuman
ID: 6993415
I've wrapped your code in a couple of classes, objects (I bet that name gets awfully ambiguous in detailed conversations ^_^).

Here's what I've got. It compiles and runs fine:

//======== HashEnumerator.java

import java.util.Enumeration;
import java.util.Hashtable;
public class HashEnumerator {
     private Enumeration e;
     private Hashtable ht;

     public static void main (String args[]) {
          Hashtable ht = new Hashtable ();
          ht.put ("one", new Integer (1));
          ht.put ("two", new Integer (2));
          ht.put ("three", new Integer (3));
          ht.put ("four", new Integer (4));
          ht.put ("five", new Integer (5));
          ht.put ("six", new Integer (6));

          HashEnumerator henum = new HashEnumerator (ht);
          while (henum.hasNext ()) {
               HashElement he = henum.next ();
               System.out.println ("Key: " + he.getKey () + "\tValue: " + he.getValue ());
          }
     }

     public HashEnumerator (Hashtable ht) {
          this.ht = ht;
          e = ht.keys ();
     }

     public boolean hasNext () {
          return e.hasMoreElements ();
     }

     public HashElement next () {
          Object k, v;
          if (e.hasMoreElements ()) {
               k = e.nextElement ();
               v = ht.get (k);
               return new HashElement (k, v);
          }
          else
               return null;
     }
}


//================= HashElement.java

import java.util.Hashtable;

public class HashElement {
     private Object key;
     private Object value;

     public HashElement (Object key, Object value) {
          this.key = key;
          this.value = value;
     }

     public Object getKey () {
          return key;
     }

     public Object getValue () {
          return value;
     }
}

=============================

Before I close this thread, can you spot any potential issues in there that will need addressing? It looks ok to me, but I haven't really used hashes much before so there might be something I'm missing.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 92

Expert Comment

by:objects
ID: 6993445
Looks ok to me :)
0
 
LVL 1

Author Comment

by:Subhuman
ID: 6993510
Cool, thanks a lot. Enjoy the points. ^_^
0
 
LVL 92

Expert Comment

by:objects
ID: 6993525
Thanks mate :-)
Let me know if you have any problems.

http://www.objects.com.au
Brainbench MVP for Java 1
http://www.brainbench.com
0
 
LVL 9

Expert Comment

by:doronb
ID: 6993976
Hi,


Just tried to stick with your Iterator approach.


Doron
0
 
LVL 1

Author Comment

by:Subhuman
ID: 6995219
Heh, well thanks anyway. :)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now