I have a class A with automatically generated hashCode() and equals() methods:
public class A {
private IntegerProperty x = new SimpleIntegerProperty();
private IntegerProperty y = new SimpleIntegerProperty();
public Coordinate(int x, int y) {
this.x.set(x);
this.y.set(y);
}
public int getX() {
return x.get();
}
public void setX(int x) {
this.x.set(x);
}
public int getY() {
return y.get();
}
public void setY(int y) {
this.y.set(y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
A other = (A) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
if (y == null) {
if (other.y != null)
return false;
} else if (!y.equals(other.y))
return false;
return true;
}
...
}
And an enumeration:
public enum E {
S1,S2;
...
}
In my main method I have the following HashMap:
private ObservableMap<A, E> m = FXCollections.observableMap(new HashMap<>());
A a1 = new A(0,0);
A a2 = new A(0,0);
E e1 = E.S1;
m.put(a1, e1);
System.out.println(m.get(a1)); // S1
System.out.println(m.get(a2)); // null
I suppose it's the equals() method which is broken, because normally with int values instead of IntegerPropertiy the second println(...) shouldn't print null.
Does anyone have an idea how to fix this?
nullbecause you don't have a key in your map, you didn't put anya2to your map.