Sonic and Sega Retro Message Board: Java Question Regarding Hashtables - Sonic and Sega Retro Message Board

Jump to content

Hey there, Guest!  (Log In · Register) Help
Page 1 of 1
    Locked
    Locked Forum

Java Question Regarding Hashtables

#1 User is offline saxman 

Posted 10 May 2012 - 09:37 PM

  • S2HD Staff - Tools & Assistant Programmer
  • Posts: 2591
  • Joined: 08-April 04
  • Gender:Male
  • Location:United States of America
  • Project:http://www.youtube.com/watch?v=oSkQoKRovEk
  • Wiki edits:136
I'm doing a training program with a company, and one of the projects involves creating a Hashtable with numbers from 1-10 in it. I have to transfer those numbers into another Hashtable. I've been working with it for the last hour and can't figure it out. Here's what I have so far...

import java.util.Hashtable;

public class Q3 {
	
	public static void main(String[] args)
	{
		Hashtable<String, Integer> tableSrc = new Hashtable<String, Integer>();
		Hashtable<String, Integer> tableDest = new Hashtable<String, Integer>();
		
		tableSrc.put("One", 1);
		tableSrc.put("Two", 2);
		tableSrc.put("Three", 3);
		tableSrc.put("Four", 4);
		tableSrc.put("Five", 5);
		tableSrc.put("Six", 6);
		tableSrc.put("Seven", 7);
		tableSrc.put("Eight", 8);
		tableSrc.put("Nine", 9);
		tableSrc.put("Ten", 10);
	}

}



Can anybody show me a way I can transfer the contents from tableSrc to tableDest?

#2 User is offline Conan Kudo 

Posted 11 May 2012 - 09:52 AM

  • 「真実はいつも一つ!」工藤新一
  • Posts: 477
  • Joined: 12-January 09
  • Gender:Male
  • Wiki edits:14
According to the Java spec, you can do shallow copies with clone(), but that means that the destination hash table really only has pointers/references to the source hash table. The only way to duplicate a hash table in Java is to iterate through the source hash table and copy them one by one into the destination hash table.

Most hash table implementations are like this. Even C++11 hash tables are like this.

#3 User is offline Glitch 

Posted 11 May 2012 - 03:30 PM

  • Posts: 155
  • Joined: 22-September 08
  • Gender:Male
  • Project:Sonic 2 LD
  • Wiki edits:22
Hashtable also has a copy ctor that's subtly different from clone(): clone performs a copy of the backing entry table, thus does not need to recompute the hash, whereas the copy ctor essentially does what Conan Kudo suggests and iterates the Hashtable calling put(key,value) for each entry. Either way is acceptable since both String and Integer are immutable.

Something worth noting: Hashtable is internally synchronized so if you're only accessing it from one thread you'll get better performance out of a HashMap. Even if you are dealing with a multithreaded application you might want to consider ConcurrentHashMap (Hashtable is legacy code).

Page 1 of 1
    Locked
    Locked Forum

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users