This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes how to access hashtable from object array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to access hashtable from object array " Watch "how to access hashtable from object array " New topic
Author

how to access hashtable from object array

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Hello all
I have simple object array that contains hashtable
is there any way to access the object that contains the hashtable
whith out first to get the hashtable to tmp hashtable

Object[] objs = new Object[1];
objs[0] = new Hashtable().put("myKey","nada");

like something like that (does not work):
String s = objs[0].get("myKey");
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
You would have to cast the reference from index 0 of the array to a Hashtable before you invoke the get() method on it.
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
still geting error if i try to cast like this :
String s = (Hashtable)objs[0].get("myKey");

The method get(String) is undefined for the type Object
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
I think operator precedence is possibly tripping you up here (make sure your cast to Hashtable happens before the get() invocation). You would also need to cast the result of the get() method to a String before you can set the String reference to it.
Simon Baker
Ranch Hand

Joined: Sep 09, 2004
Posts: 57
For clarification:

The differences are: cast obj[0] to Hashtable before invocation of get(); cast result of get() to String before assigning to reference s; separate constructor of Hashtable from put() invocation.

On the last point, the get() method on a Hashtable returns the previous value for the same key (or null if none existed). This is what you were assigning object reference objs[0] to. I suspect you intended that reference to be assigned to the Hashtable itself.
 
GeeCON Prague 2014
 
subject: how to access hashtable from object array