package point;
//an array arr is populated with random x,y points using MyPoint then
public static void main(String[] args) throws IOException {
HashMap<MyPoint,Integer> map = new HashMap<MyPoint,Integer>();
Integer val =0;
for(int i = 0; i < arr.length ; i++)
{
map.put(arr[i],val);
}
}
//second file.
package point;
public class MyPoint implements Comparable<MyPoint>{
private int x;
private int y;
public MyPoint(int x1, int y1) {
x = x1;
y = y1;
}
public boolean equals(Object p) {
MyPoint p1;
try {p1 = (MyPoint) p;}
catch (ClassCastException ex) {return false;}
return (x == p1.x) && (y == p1.y);
}
public int hashCode() {
return ((y * 31) ^ x);
}
Here is my code MyPoint stores x y points. I’m using this code to get unique sets of x,y points with no duplicates.
My Question is how do I retrieve the x y values in MyPoint ? Is this an efficient way to use a HashMap to filter unique X,Y points. Also here is the HashCode I made.
Is there a better HashCode I could use?
An easy way would be to make getter methods for x and y:
As for a HashMap, you could have it map from X coordinates to a list of MyPoints with that X coordinate and unique Y coordinates (HashMap). However, if all you’re looking for is uniqueness, you could just store every MyPoint in a set/ArrayList and see if a similar point already exists, using your .equals() method. Hope that helps!