简体   繁体   中英

Java HashMap “put” method in a for loop

I am facing an issue while using HashMap in a for loop. 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.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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