列表问题

1 java

我是一个java新手,并且遇到了一些"java.util.List"的问题.Below是我的代码,我正在尝试创建一个对象列表,但我得到的结果是不受欢迎的.你能帮帮我吗解决问题.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

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}]
Run Code Online (Sandbox Code Playgroud)

===============

为什么我没有得到具有不同值的对象.通过我的代码帮助我解决问题..

aio*_*obe 6

你要加childRowMap两次.

请注意,您要添加的参考childRowMap.这意味着从索引0和索引1的引用都可以看到对地图的更改,这就是为什么它看起来像你添加了两个相同的对象.

您可以通过在循环中的每次迭代创建一个新映射来修复它:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Adding object in the postition 0
Adding object in the postition 1
[{encodedValue= enc0, startDate=startDate0, endDate=endDate0},
 {encodedValue= enc1, startDate=startDate1, endDate=endDate1}]
Run Code Online (Sandbox Code Playgroud)