Link to home
Start Free TrialLog in
Avatar of Nuttman
Nuttman

asked on

How do i use an iterator to get data from a hashtable?

I am having a bit of trouble understanding collections in Java and how they relate to iterators.

I have a hashtable  - ResTable(res, value); and i need to use an iterator to go through each element in my hash table and copy the value res into a string array and also copy value into a separate int array.  How do i go about defining the iterator for my hashtable?
 
 
private static void CopyToArray(){
       
// I know that i have to define my collection by something like...  
   Collection myCollection = .....;  //  do i assign ResTable equal to mycollection?    How??
//Then i can say...
   Iterator i = myCollection.iterator();
   while (i.hasNext()){
      System.out.println(i.next());
      // Do what i need to to convert data from hash table to array
      //Cast datatype etc
   }
}
 

Any seggestion in either code format, psuedocode or basic english would be much appreciated.

Nutty
Avatar of rjackman
rjackman

it seems that u want to get the values without knowing the keys in the table then u can do the following
Set keys = ResTable.keySet();
for(Iterator itr = keys.iterator();itr.hasNext();)
{
   String key = (String)itr.next();
   System.our.println("Keys---->"+key);
   System.out.println("Value--->"+ResTable.get(key));
}

cheers
RJ
You don't need to assign ResTable to Collection. Because it is already a Collection.

To extract the keys of ResTable into String array,
String[] strArr = (String[]) ResTable.keySet().toArray(new String[0]);

For values, You can only copy into Integer object but not int primitive type.

Integer[] iArr = (Integer[]) ResTable.values().toArray(new Integer[0]);
ASKER CERTIFIED SOLUTION
Avatar of jose_tijo
jose_tijo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- points to jose_tijo

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

vemul
Cleanup Volunteer
Comment from expert accepted as answer

Computer101
E-E Admin