2

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]}

2 Answers 2

5

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]}
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

I would move the declaration inside the loop as well.
It works well.. Thanks Peter Lawrey and dystroy for quick respond.
In this way, if your i is very big, there may be too many new created objects. Better way to avoid this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.