> How can I copy a Hashtable into an object?
What is it exactly what you want to copy? The reference to a Hashtable -
this is what your code does. The structure of the Hashtable? Then
clone() the Hashtable - this gives you a shallow copy. If you need a
deep copy you have to write your own code which iterates over the
contents of one Hashtable and clones each value (there is no need to
clone the keys, since keys should better be immutable anyhow to get a
working Hashtable, so references to keys can be copied instead of the
keys need cloning).
Also, copying something into an object requires the existence of such an
object. In your code, however, there is no such object. There is just a
reference (variable) which can point to an object (local_copy).
Note, however, that the need to clone/copy a data structure like a
Hashtable is a rare case. You should check your design if you really
need copies hanging around in your code. Hashtables, like many other
collections are often used as some kind of central "data base", where
every part of the code which uses it wants to have the same view on the
data. And not some outdated copy.
> class gc {
The almost universally applied convention in Java is that class names
start with an upper-case letter.
> Hashtable local_copy;
This is just a variable which can reference a Hashtable. This is not a
Hashtable object. And you never create a particular Hashtable object.
> public void gc() {
>
> }
>
> public void setHash(Hashtable in) {
> local_copy = in;
For a shallow copy - if this is what you want:
local_copy = (Hashtable) in.clone();
But, before you do it, make yourself familiar with what the term
"shallow copy" means.
> }
>
> public Hashtable getHash() {
> // this local_copy is empty!!!
> return local_copy;
> }
It is not empty. local_copy is either null (if setHash() was never
called, or called with a null argument), or it is a reference to the
original 'in' Hashtable. In case that original 'in' Hashtable didn't
contain any data, then copying the reference to it of course doesn't
magically add data.
/Thomas

Signature
The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
> Hi,
>
[quoted text clipped - 19 lines]
>
> }
Not quite sure what you mean, but your code seems to be fine:
jc@soyuz:~/tmp> cat hashcopy.java
public class hashcopy {
public static class gc {
java.util.Hashtable local_copy ;
public void gc() {}
public void setHash(java.util.Hashtable ht) {
local_copy = ht ;
}
public java.util.Hashtable getHash() {
return local_copy ;
}
}
public static void main(String [] asArgs) {
gc gcTemp = new gc() ;
System.out.println("gc.getHash(): " + gcTemp.getHash()) ;
java.util.Hashtable htTest = new java.util.Hashtable() ;
htTest.put("hello", "there") ;
gcTemp.setHash(htTest) ;
System.out.println("gc.getHash(): " + gcTemp.getHash()) ;
}
}
jc@soyuz:~/tmp> java hashcopy
gc.getHash(): null
gc.getHash(): {hello=there}