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