Zipher200
Zipher200

Reputation: 11

Java: local Hashtable overwriting global Hashtable

While performing actions on a locally defined Hashtable, the global Hashtable of another class that was assigned to the local Hashtable also has these actions performed on it. I'm not sure if this is some simple problem that should be obvious, but I could not find any questions about it.

public void redraw(String[] sNewEntity,Hashtable<String,Entity> h){
    Hashtable<String,Entity> htEntities=h;

    htEntities.remove(sNewEntity[0]);
    //many lines of code that ensures that the removal doesn't invalidate anything
    if(validation==true){
        m_HomeFrame.graph=new mxGraph();
        m_HomeFrame.myGraphComponent = new mxGraphComponent(m_HomeFrame.graph);        
        m_HomeFrame.setScroll(m_HomeFrame.myGraphComponent);
        m_HomeFrame.m_Tree.h_entityTable=htEntities;
    }
}

This is the function. All variables with "m_"- are globals. This method takes a string array and hashtable and removes the item of the hashtable that has a key of the string array's first item. The problem is that the global hashtable (m_HomeFrame.m_Tree.h_entityTable) updates as soon as it hits (htEntities.remove(sNewEntity[0]);). Is there a way to disassociate htEntities from the global variable? Also, apologies for not using Generics. I saw that quite often when searching for hashtable stuff.

Upvotes: 1

Views: 462

Answers (1)

christopher
christopher

Reputation: 27356

When you pass in h, you're not passing in the actual HashTable object. You're passing in a reference to the HashTable object. This means that when you make a change to h, you're making a change to the same Object.

The way to get around this is to use the new keyword. This will force the Java runtime to create a new HashTable object.

Upvotes: 4

Related Questions