简体   繁体   中英

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

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 hence 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM