简体   繁体   English

无法从使用 arraylist 作为值的 hashmap 获取值已清除

[英]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.我正在研究一段代码,它有一个 Hashmap。 This hashmap has a string as key and an arraylist as value.这个 hashmap 有一个字符串作为键和一个 arraylist 作为值。 I populate the arraylist and then put the value into the hashmap.我填充 arraylist,然后将值放入 hashmap。 After putting the value, I want to clear the arraylist so that no old values are present.输入值后,我想清除 arraylist 以便不存在旧值。

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.现在,当我尝试从 hashmap 打印值时,我没有得到任何内容。 This maybe because of the arraylist.clear().这可能是因为 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.此外,我不想为每个数据创建新的 arraylist,因此我想删除内容但它不起作用。

Any way to go about this. go 关于此的任何方式。

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. 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.一个在 hashmap 中被称为“元素”。 And then you r deleting all elements from your arraylist.然后你 r 从你的 arraylist 中删除所有元素。 Ofcause you will lose everething.因为你会失去一切。 So now you still has two links but to the empty arraylist所以现在你仍然有两个链接,但指向空的 arraylist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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