Zip*_*Zip 2 java arraylist hashmap
我对这些hashmap的arraylist真的很陌生.我想创建一个hashmap的arraylist,并将动态地更改循环中的arraylist元素.我的代码如下:
static List<HashMap<Character, Integer>> column = new ArrayList<HashMap<Character, Integer>>(9);
static HashMap<Character, Integer> columns = new HashMap<Character, Integer>();
for(int i=0;i<9;i++)//initialize?
column.add(i, columns);
for(int i=0;i<9;i++)
column.get(i).put(b[xxx][xxx],(int)(b[xxx][xxx]));
Run Code Online (Sandbox Code Playgroud)
起初我没有在这里使用for循环,我认为我在第一行初始化arraylist大小(9)就足够了,但是当我试图获取元素时column.get(5).put(something),它给了我异常IndexOutOfBound.
然后我试着用它column.add(i, null);,但它给了我例外NullPointerException.所以我改变了这个column.add(i, columns);
但现在问题是,当我尝试编辑columnarraylist中的一个hashmap时,arraylist中的每个其他hashmap也会被更改,我想这是因为它们首先被设置为相同的columnshashmap?
所以我的问题是如何初始化hashmaps的arraylist,这样我每次都可以改变它们中的每一个而不影响其他的?
你不想写
column.add(i, columns);
Run Code Online (Sandbox Code Playgroud)
这会不断添加对它的引用HashMap.column然后会有9个对同一个对象的引用,所以当一个对象发生变化时,它们都会发生变化.
相反,你想要
column.add(i, new HashMap<Character, Integer>());
Run Code Online (Sandbox Code Playgroud)
然后每次都添加一个新实例.
| 归档时间: |
|
| 查看次数: |
2193 次 |
| 最近记录: |