Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Strings can cover a lot of use cases, but using more complicated objects can give you a lot more flexibility in your code. Seeing that in the US they've just announced the NCAA college basketball tournament seeds, I'll see if I can come up with a tournament-themed example.</p> <p>Suppose I want to build a Hashmap that stores all of the teams that are in each region. There are four regions to the tournament: East, West, Southwest, and Southeast. You could certainly create your map as:</p> <pre><code>HashMap&lt;String, List&lt;Team&gt;&gt; teamsInRegions = new HashMap&lt;String, List&lt;Team&gt;&gt;(); </code></pre> <p>But then, what if you already have an object that represents a region? You likely would, since each region has a lot more information associated with it than a name. For instance, I figure a Region class might look like:</p> <pre><code>public class Region { private String name; private Calendar firstRound; private String firstRoundLocation; private Calendar secondRound; private String secondRoundLocation; private Calendar thirdRound; private String thirdRoundLocation; .... } </code></pre> <p>You get the idea. If the HashMap were keyed by a String, you could certainly get away with having a reasonable Region.toString() method and using that as the key, but using the more complex object will allow you to write more flexible code.</p> <p>While others may disagree, I find myself using Maps in somewhat unpredictable ways sometimes, where calling HashMap.keySet() gives me a Set of fully populated, complex objects with a plethora of information. <strong>And</strong> having the Map there means I can use those objects to make decisions elsewhere as well.</p> <p>For instance, suppose I wanted to build up a list of all the locations of all the games in the basketball tournament. If I had my HashMap with complex objects, that would be as simple as:</p> <pre><code>Set&lt;Region&gt; regions = myMap.keyset(); Set&lt;String&gt; gameLocations = new HashSet(); for (Region region : regions) { gameLocations.add(region.getAllLocales()); } </code></pre> <p>And so on. YMMV.</p>
 

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