I am having trouble on how to retrieve the Value from a Map indexed with custom Objects. In my case I have a Map with a Model object as Key and a List of objects as Value. The Map seems to be well populated because I've iterated through each Key and printed all Model objects to console.
My question is how to get Value from a specific entry in the Map.
Map<Model, Parameter> mapSet = m.getMyMap()
for(Entry<Model, Parameter> entry : mapSet){
println entry.key.getModel() //prints each Model
}
List<Parameter> testListBase = mapSet.get(new Model("BASE"))
List<Parameter> testListSearch = mapSet.get(new Model("SEARCH"))
Do I have to override hashCode() and equals() from Object to retrieve the list for that entry in the Map?
UPDATE
Here it is the simple Model object, but still cannot retrieve the key using
mapSet.get(new Model("BASE"))
public final class Model {
private final String model;
private final static int count = 0;
private int id;
private Model(String model){
this.model = model;
id = ++count;
}
private String getModel(){
return model;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((model == null) ? 0 : model.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;
}
Model other = (Model) obj;
if (id != other.id) {
return false;
}
if (model == null) {
if (other.model != null) {
return false;
}
} else if (!model.equals(other.model)) {
return false;
}
return true;
}
}
assert new Model ("hello") == new Model ("hello")fails because both models have different id's. You can fix this by excluding the id from the hashCode and equals.hashCode()andequals()and now I have a StackOverflowErrorhashCode()andequals()delegate to theStringmodel. Ex:public int hashCode() { model.hashCode() },public boolean equals(Object obj) { model.equals(obj) }.