Home arrow static arrow Java Programming [Archive] - Array of hashtable
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Array of hashtable
This topic has 5 replies on 1 page.

Posts:10
Registered: 3/3/04
Array of hashtable  
Jul 1, 2004 10:27 PM



 
Hi,

Following is my code :
-----------------Code starts here------------------------------------------------------------
import java.util.Hashtable;

public class Test{
public static void main(String arg[]){
Hashtable ht=new Hashtable();
Hashtable[] hta=new Hashtable[3];

ht.put("Country","Japan");
ht.put("City","Tokyo");

hta[0]=ht;

ht.put("Country","India");
ht.put("City","Delhi");

hta[1]=ht;

System.out.println(hta[0].get("Country"));
System.out.println(hta[1].get("Country"));
}
}

----------------Code ends here-------------------------------------------------------------------

And the result is....
-----Output-----------------------
India
India
-----Output ends here---------

While I was expecting....
Japan
India

Why hashtable in hta[0] is over-written ? How can I achieve the result (Japan, India) ?

Thanks,
 

Posts:111
Registered: 12/21/97
Re: Array of hashtable  
Jul 1, 2004 10:37 PM (reply 1 of 5)



 
that 'cos you are using the same instance of the hashtable, in another word, both hta[0] and hta[1] are referencing the same hashtable, that's why the values are overwritten. you should create a new instance of hashtable for each element in the array.
 

Posts:1,995
Registered: 12/10/00
Re: Array of hashtable  
Jul 1, 2004 10:39 PM (reply 2 of 5)



 
You instantiate the Hashtable only once(your ht instance) and both hta[0] and hta[1] point to it so you overwrite your values.
A possible solution is to call
ht = new Hashtable();

after hta[0]=ht;

BTW unless you really need synchronization you can consider using HashMap instead of Hashtable

HTH
Mike
 

Posts:1,995
Registered: 12/10/00
Re: Array of hashtable  
Jul 1, 2004 10:40 PM (reply 3 of 5)



 
Beaten ;)
 

Posts:453
Registered: 11/6/04
Re: Array of hashtable  
Jul 1, 2004 10:42 PM (reply 4 of 5)



 
ht.put("Country","Japan");
ht.put("City","Tokyo");

hta[0]=ht;

After this, both hta[0] and ht are references to the same hashtable object

ht.put("Country","India");
ht.put("City","Delhi");

Here, you are modifying the same object referenced by ht and hta[0]

hta[1]=ht;

Here ht, hta[0],hta[1] all reference the modified object and

hence your result
 

Posts:10
Registered: 3/3/04
Re: Array of hashtable  
Jul 2, 2004 12:26 AM (reply 5 of 5)



 
Thankyou bellyripper and Jsweep to remind me basic Java.
 
This topic has 5 replies on 1 page.