开发者

Unable to get values from a hashmap which uses a arraylist as value is cleared

开发者 https://www.devze.com 2023-03-18 07:05 出处:网络
I am working on a piece of code which has a Hashmap. This hashmap has a string as key and an arraylist as value. I populate the arraylist and then put the value into the hashmap. After putting the val

I am working on a piece of code which has a Hashmap. This hashmap has a string as key and an arraylist as value. I populate the arraylist and then put the value into the hashmap. After putting the value, I want to clear the arraylist so that no old values are present.

Please see below code:

ArrayList<Bean> elements = new ArrayList<Bean>();

        for(int j=0; j<array.length; j++){
            String[] id = {"2439","70212","9021","0104","0255","10353","3889","8990","10277"};
            String[] Title = {"Gulliver","Good=Guys","Gnomeo","Gene","ABCD","High","Green=Lantern","Gnomeo2","WXYZ"};
            for(int i=0; i<id.length; i++){
                Bean bean = new bean();
                bean.ID(id[i]);
                bean.Title(title[i]);
                elements.add(bean);
            }
            udbResults.put(array[j], elements);
            elements.clear();
        }

Now when i try to print the values from the hashmap, i am not getting any content. This maybe because of the arraylist.clear(). Why does this happen?

Also I didnt want to create new arraylist for each data henc开发者_开发知识库e i wanted to remvoe the contents but its not working.

Any way to go about this.

Thanks,

swati


what you r doing is simply createing and populating an arraylist, then you are puting a link to arraylist into hashmap...so now you have 2 links for one arraylist. One was called 'elements' another in hashmap. And then you r deleting all elements from your arraylist. Ofcause you will lose everething. So now you still has two links but to the empty arraylist

0

精彩评论

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