Solved

Get both key and value from Hashtable element.

Posted on 2002-05-07
9
377 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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

697 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