To give a simple example, consider a Place class:
public class Place {
//fields
private String name;
private String state;
private int population;
private int squareMileage;
private int elevation;
//constructors
public Place() {
}
public Place(String name, String state) {
this.name = name;
this.state = state;
}
public Place(String name, String state, int population, int squareMileage,
int elevation) {
this.name = name;
this.state = state;
this.population = population;
this.squareMileage = squareMileage;
this.elevation = elevation;
}
//getters and setters
public String getName() {
return this.name;
}
public String getState() {
return this.state;
}
//... (other getters and setters omitted)
//do stuff
}
And a Places class (a HashMap of Place objects):
import java.util.*;
public class Places {
private Map searchablePlaces;
public Places() {
searchablePlaces = new HashMap();
}
public void add(Place value) {
Place key = new Place(value.getName(), value.getState());
searchablePlaces.put(key, value);
}
public Place find(Place key) {
return searchablePlaces.get(key);
}
//override hashCode, equals
//do stuff
}
Essentially, my question is:
- Would there be any efficiency gained in searching the
HashMapforkey, as opposed to searching forvaluedirectly in, let’s say, a sortedArrayList? - What if
keywas of typeStringequal toname + state(or of typeString[2])?
It’s confusing, IMHO. I would define a PlaceKey class, holding just a name and a state and defining hashCode and equals. A place would hold a PlaceKey, and other attributes. And I would use a
Map<PlaceKey, Place>.Note that, in your example, it’s the Place class that needs equals and hashCode, not the Places class.
Now, to answer your 2 questions :