?
Solved

Get both key and value from Hashtable element.

Posted on 2002-05-07
9
Medium Priority
?
390 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 1200 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month15 days, 19 hours left to enroll

850 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