关于List<Map>中赋值的疑惑
publicstaticvoidmain(String[]args){//list赋值Listlist=newArrayList();Mapmap=newHashMap(...
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);
}
程序中只改变了第3个map的值,但是第1个map的值也跟着改变了,有无方法只改变第3个map的值 展开
//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);
}
程序中只改变了第3个map的值,但是第1个map的值也跟着改变了,有无方法只改变第3个map的值 展开
2个回答
展开全部
这个很容易解释,因为list.get(2)存的是引用,而list.get(2)和list.get(0)存放的是相同饮用,内存里面同一个区域,只要一个改变,其他都会改变。
改乘这样就行了
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);
}
}
改乘这样就行了
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);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询