I have code that looks like the following:
private void MethodToDo(SpecialObject o) {
Map<InfoObj, Integer> totalNeeds = new HashMap<InfoObj, Integer>();
for (ListObject obj : o.getListOfObjects()) {
InfoObj infoObj = new InfoObj(obj.getTitle(), obj.getId());
Integer need = totalNeeds.get(infoObj);
if (need == null) {
need = new Integer(obj.getNeeded());
} else {
need = need + obj.getNeeded();
}
totalNeeds.put(infoObj, need);
}
}
The object is a private inner class (in the same class as that method) that looks like this:
private class InfoObj {
private String title;
private Integer id;
public InfoObj(String title, Integer id) {
this.title = title;
this.id = id;
}
public String getTitle() {
return title;
}
public Integer getId() {
return id;
}
@Override
public boolean equals(Object io2) {
if (this == io2) { return true; }
if ( !(io2 instanceof InfoObj) ) { return false; }
InfoObj temp = (InfoObj) io2;
return this.id.equals(temp.id) && this.title.equals(temp.title);
}
@Override
public int hashCode() {
final int prime = 7;
int result = 1;
result = prime * result
+ ((this.title == null) ? 0 : this.title.hashCode());
result = prime * result
+ ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
However, despite overriding the equals and hashCode methods, the hashMap will still contain repeat keys (as in title and id are equivalent…but still show up in multiple places). I think I’m doing everything correctly, but realize I could be missing something…
Also, I know there are repeat keys because I loop through the keySet and output the results, which results in objects with the same title and id showing up multiple times.
Per your comment, a HashMap cannot contain the same keys per the implementation the same key would be:
And since you are following the contract for equals and hashcode, any object you create here:
With the same id and title, will be considered the same
key, and if the map previously contained a mapping for the key, the old value is replaced.