I want to store different values for unique coordinates.I am using integer array to store those values in HashMap to corresponding coordinates but every key maps to last calculated value.
Code :
import java.util.*;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Solution
{
@SuppressWarnings("empty-statement")
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
Integer[] ar = new Integer[3];
Map<Point, Integer[]> map = new HashMap<>();
for (int a0 = 0; a0 < m; a0++) {
Point p = new Point(in.nextInt(), in.nextInt());
int a = in.nextInt();
int b = in.nextInt();
if (map.containsKey(p)) {
if (map.get(p)[2] < (a - b)) {
ar[0] = a;
ar[1] = b;
ar[2] = a - b;
map.put(p, ar);
}
} else {
ar[0] = a;
ar[1] = b;
ar[2] = a - b;
map.put(p, ar);
}
}
Set<Entry<Point, Integer[]>> set = map.entrySet();
List<Entry<Point, Integer[]>> list = new ArrayList<>(set);
for (Map.Entry<Point, Integer[]> entry : list)
System.out.println(entry.getKey() + " ==== " + Arrays.toString(entry.getValue()));
}
}
Input :
3 3
0 1 1 1
1 2 2 4
2 0 1 2
Result :
java.awt.Point[x=0,y=1] ==== [1, 2, -1]
java.awt.Point[x=1,y=2] ==== [1, 2, -1]
java.awt.Point[x=2,y=0] ==== [1, 2, -1]
You only have one single instance of your
ar
array and you are just storing it under multiple keys. You need to create a new array instance each time:Output:
(Also note that
n
isn't actually read anywhere.)For a better understanding consider this simplified example:
Output:
What you can see here is
arr[0]
to 2, the value for key 1 has also changed in the map