我是一个 Java 新手,对“java.util.List”有一些疑问。下面是我的代码,我试图在其中创建一个对象列表,但我得到的结果并不理想。你能拜托吗帮我解决这个问题。
import java.util.*;
class testMap
{
public static void main(String[] args)
{
HashMap<String,Object> childRowMap = new HashMap<String, Object>();
List <Object> actList= new ArrayList <Object> ();
for (int x=0;x<2 ;x++ ){
if(x==0){
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
}
else if (x==1){
childRowMap.put("startDate","startDate"+x);
childRowMap.put("endDate","endDate"+x);
childRowMap.put("encodedValue"," enc"+x);
}
System.out.println("Adding object in the postition "+ x);
actList.add(x,childRowMap);
}
System.out.println(actList);
}
}
结果:
Adding object in the postition 0
Adding object in the postition 1
[{encodedValue= enc1, startDate=startDate1, endDate=endDate1}, {encodedValue= en
c1, startDate=startDate1, endDate=endDate1}]
===============
为什么我没有得到具有不同值的对象。请帮助我找出代码中的问题..
最佳答案
您要添加两次 childRowMap
。
请注意,您正在将 reference 添加到 childRowMap
。这意味着对 map 的更改将从索引 0 和索引 1 处的引用可见,这就是为什么看起来您添加了两个相同的对象。
您可以通过在循环中的每次迭代创建一个新 map 来修复它:
import java.util.*;
class testMap {
public static void main(String[] args) {
.-------
|
| List<Object> actList = new ArrayList<Object>();
|
| for (int x = 0; x < 2; x++) {
|
'---------> HashMap<String, Object> childRowMap = new HashMap<String, Object>();
if (x == 0) {
childRowMap.put("startDate", "startDate" + x);
childRowMap.put("endDate", "endDate" + x);
childRowMap.put("encodedValue", " enc" + x);
} else if (x == 1) {
childRowMap.put("startDate", "startDate" + x);
childRowMap.put("endDate", "endDate" + x);
childRowMap.put("encodedValue", " enc" + x);
}
System.out.println("Adding object in the postition " + x);
actList.add(x, childRowMap);
}
System.out.println(actList);
}
}
输出:
Adding object in the postition 0
Adding object in the postition 1
[{encodedValue= enc0, startDate=startDate0, endDate=endDate0},
{encodedValue= enc1, startDate=startDate1, endDate=endDate1}]
关于java - 列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6391394/