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.
The almost universally applied convention in Java is that class names
start with an upper-case letter.
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