tags:

views:

205

answers:

2

I have the following piece of code :

private static HashMap<String, TestObject> labelHash= new HashMap<String, TestObject>();
    private static HashMap<String, TestObject> valueHash= new HashMap<String, TestObject>();

    private HashMap getChildrenInHash(int opt){
//       HashMap labelHash= new HashMap();
//       HashMap valueHash= new HashMap();

        if (valueHash.isEmpty() && labelHash.isEmpty()) {        

                if(getLabel().isShowing()){
                    TestObject[] tempArray = getLabel().getMappableParent().getMappableChildren();
                    for(int i =1; i < tempArray.length-2;i++){
                        if(tempArray[i]==null)
                            break;
                        if(tempArray[i].getProperty("text").toString().compareTo(" ")==0){
                            i+=1;

                        }
                        labelHash.put((String)tempArray[i].getProperty("text"),(tempArray[i]));

                        valueHash.put((String)tempArray[i].getProperty("text"),(tempArray[i+1]));
                        i+=2;
                }
                //System.out.println("finished filling the hashes");                
                }
            }            

        }

        if(opt ==1)
            return labelHash;
        else 
            return valueHash;

    }

I use this method to basically populate initially the hashmaps then ultimately to get values out of it later, but the problem is that values what I see get populated in does not exist anymore for retrieval (not all, but some) ? so what is going on ? how do they get lost, I checked with debugger and saw values one by one when inserted, but when retrieved not exist anymore, any thoughts ?

A: 

Are you doing anything with these TestObjects?

HashMaps (and collections in general) store a reference rather than a new copy of their contents. That's OK with immutable classes, such as String, but with non-Immutable classes, you can modify these objects contents through the original reference.

R. Bemrose
yes, at the end I'm getting out values out of it, depending on widgets, it's for automated UI testing.
Tiberiu Hajas
A: 

Do you use different keys (always) when populating ? If you always use the same key then you will only find the last inserted value...

pgras
pretty much always the same values, however sometimes rarely are different (from one runtime to another).
Tiberiu Hajas