Hi i have working code but i would like to print out the coordinates. there is a hashmap that holds Coordinates and Strings. there is a class for Coordinates to allow me to put Coordinates in but when i try to print out it gets confused im clearly not doing something right. Thanks for looking
public class XYTest {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
}
}
You have to override
toString()in your Coords class.What is confusing you is something like this:
What is this? It is the result of the original
toString()method. Here is what it does:So, overriding it with your own code will get rid of the confusing output 🙂
Please note that your having great hash-collisions. A much better hashCode() implementation would be:
To demonstrate your bad hash code: Some collisions: