您的位置:首页 > 其它

List<Map>中赋值覆盖问题

2016-01-06 10:37 537 查看
public static void main(String[] args) {
//list赋值
List list = new ArrayList();
Map map = new HashMap();
map.put("id", 1);
list.add(map);
Map map2 = new HashMap();
map2.put("id", 2);
list.add(map2);
System.out.println(list);
//newList = list*2
List newList = new ArrayList();
newList.add(list.get(0));
newList.add(list.get(1));
newList.add(list.get(0));
newList.add(list.get(1));
System.out.println(newList);
//改变第3个map的id值
for(int i=0;i<newList.size();i++){
if(i==2){
Map m = (Map)newList.get(2);
m.put("id", 3);
}
}
System.out.println(newList);
}




虽然修改的的是newList的第三个对象,但第一个对象id值也改变。
因为list.get(2)存的是引用,而list.get(2)和list.get(0)存放的是相同引用,内存里面同一个区域,只要一个改变,其他都会改变。

<span style="color:#ff0000;">改乘这样就行了
</span><span style="background-color: rgb(204, 204, 204);">import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Dog {

public static void main(String[] args) {
List list = new ArrayList();
Map map = new HashMap();
map.put("id", 1);
list.add(map);

Map map2 = new HashMap();
map2.put("id", 2);
list.add(map2);

System.out.println(list);

// newList = list*2
List newList = new ArrayList();
newList.add(list.get(0));
newList.add(list.get(1));
newList.add(list.get(0));
newList.add(list.get(1));

System.out.println(newList);

for (int i = 0; i < newList.size(); i++) {
if (i == 2) {
Map m = new HashMap();

Map n = (Map) newList.get(2);
m.put(n.keySet().iterator().next(), 3);

newList.set(2, m);
}
}
System.out.println(newList);
}

}</span>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: