Note that there are some explanatory texts on larger screens.

plurals
  1. PO(Java) When using Maps, does it make sense for a key and value to have the same type?
    text
    copied!<p>To give a simple example, consider a <code>Place</code> class:</p> <pre><code>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 }</code></pre> <p>And a <code>Places</code> class (a <code>HashMap</code> of <code>Place</code> objects):</p> <pre><code>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 }</code></pre> <p>Essentially, my question is:</p> <ol> <li>Would there be any efficiency gained in searching the <code>HashMap</code> for <code>key</code>, as opposed to searching for <code>value</code> directly in, let's say, a sorted <code>ArrayList</code>?</li> <li>What if <code>key</code> was of type <code>String</code> equal to <code>name + state</code> (or of type <code>String[2]</code>)?</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload