Solved

Get both key and value from Hashtable element.

Posted on 2002-05-07
9
378 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 
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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

728 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