If I asked you to write a program that contains people's names, and their telephone numbers, and if I entered a name in a search field, it would give me the phone number belonging to that person (assuming unique names), how would you do it?
To make it more concrete, how would you implement these two methods? Feel free to add fields to the class.
Maps are used all over the place for all sorts of things. Basically, as I already said, whenever you want to be able to look up a value given another value to use as a key. It'd be impossible to list all possible uses.
If there is a situation where in a database there are multiple records stored on the basis of Primary key And I would need to fetch the records in a java program.
Then my solution would be to fetch the primary keys in the database and store them in a Map as keys and the rest of the fields of each record against each primary key be stored as an array of Strings and added to the Map against each key.
Am I correct?
Stephan van Hulst
posted 7 years ago
No. You'd use SQL to fetch the data you need, and iterate over the returned data directly. Using a Map would duplicate the efforts already provided by the RDBMS.
When you do use a map (or any other collection or generic type), make sure to use proper type arguments.
In the example I had you code, you should use a Map<String, String>, not just Map.