Which of the following sets of data would be the best fit to be stored in an associative array?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The first possible solution, a list of recipes, does not at all take advantage of the (key, value) structure of an associative array. It's just a list of strings. So, an array would be fine.
A list of cities grouped by continent and a list of books sorted by genre fall into the same basic category. That is, they are both sortable/groupable things. In essence, they're mapping more than one value (a country/book) to a key (a continent/genre). Now, this isn't necessarily a bad thing, but it doesn't take full advantage of the associative array. A typicaly question you might want to ask in this scenario might be "Is country X in continent Y?" This question will take O ( n ) time to answer because we've tacking on arrays of countries as our values.
A simple mapping between city and population is the best fit for an associative array. The query we'd be trying to answer here is "How many people does city X have?". This is an O ( 1 ) operation with an associative array. We map 1 key to 1 value, the keys are never repeated, and the values can be repeated. This is a classic use case for any key/value store.