开发者

java hashmap values gone after rehash?

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开发者_C百科 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 ?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜