java - 列表问题

标签 java

我是一个 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/

相关文章:

java - 需要一个带有固定标题的可滚动战斧表

java - 如何远程访问@Stateless @LocalBean

java - JAX-RS : Suppress Error Message

java - 内联图像显示为附件 : JavaMail

java - 如何将从文件读取的字符串添加到ArrayList?

java - 我如何允许在 android 中搜索也适用于字符重音?

java - 使用 SSH 写入远程文件

java - 使用 aether-api 列出 sonatype Nexus 的可用版本

java - 调整窗口上的 ImageIcon 大小

java - 如何在 JAPE 右侧制作 if-else 语句?