简体   繁体   English

for循环中的Java HashMap“ put”方法

[英]Java HashMap “put” method in a for loop

I am facing an issue while using HashMap in a for loop. 我在for循环中使用HashMap时遇到问题。 Am I doing anything wrong? 我做错什么了吗? Is there any change I have to make? 我有什么需要改变的吗? Below is the code and its output. 下面是代码及其输出。

Code: 码:

public static void main(String[] args) {

    ArrayList<Double> arrBuckets = new ArrayList<Double>(3);

    HashMap<Integer, ArrayList<Double>> hashMap = new HashMap<Integer, ArrayList<Double>>();

    for(int i=1;i<5;i++)
    {
        arrBuckets.clear();
        arrBuckets.add(0,(1.0*i)) ;
        arrBuckets.add(1,(2.0*i)) ;
        arrBuckets.add(2,(3.0*i)) ;

        hashMap.put(i, arrBuckets);
    }

    System.out.println("hashMap : "+hashMap);
}

Below is Output : 以下是输出:

hashMap : {1=[4.0, 8.0, 12.0], 2=[4.0, 8.0, 12.0], 3=[4.0, 8.0, 12.0], 4=[4.0, 8.0, 12.0]}

But Output should be like : 但是输出应该像这样:

hashMap : {1=[1.0, 2.0, 3.0], 2=[2.0, 4.0, 6.0], 3=[3.0, 6.0, 9.0], 4=[4.0, 8.0, 12.0]}

When you place an object of a collection in another collection you are passing a reference to the object, not a copy of the object itself. 当将一个集合的对象放置在另一个集合中时,您正在传递对该对象的引用 ,而不是对象本身的副本。 You are only creating one List and you are adding this list four times. 您仅创建一个列表,并且将这个列表添加了四次。

I suggest you move the new ArrayList inside the loop instead of reusing the list each time. 我建议您在循环内移动新的ArrayList,而不是每次都重复使用该列表。

You can write 你可以写

Map<Integer, List<Double>> map = new HashMap<Integer, List<Double>>();
for (int i = 1; i < 5; i++)
    map.put(i, Arrays.asList(1.0 * i, 2.0 * i, 3.0 * i));
System.out.println("map : " + map);

prints 版画

map : {1=[1.0, 2.0, 3.0], 2=[2.0, 4.0, 6.0], 3=[3.0, 6.0, 9.0], 4=[4.0, 8.0, 12.0]}

That's because you always use the same arrayList : you have only one instance of ArrayList at the end and it holds the values of the last iteration. 这是因为您始终使用相同的arrayList:结尾处只有一个ArrayList实例,并且它保存上一次迭代的值。

Change your loop to 将循环更改为

for(int i=1;i<5;i++)
{
    ArrayList<Double> arrBuckets = new ArrayList<Double>(3);
    arrBuckets.add(0,(1.0*i)) ;
    arrBuckets.add(1,(2.0*i)) ;
    arrBuckets.add(2,(3.0*i)) ;

    hashMap.put(i, arrBuckets);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM