In this reading we will be introduced to the idea of a Map
, a data structure that allows us to create an association between one object (a key) and another (a value).
You can think of a map as a special type of array. In a regular array, there is association between a number (the index) and the value stored at that index. A map is similar except that the index doesn’t have to be a number, it can be any type of value you want (e.g. a String
or even a Turtle
). In fact maps are sometimes called associative arrays.
For example, we could use a Map
to create a dictionary, i.e. an association between a word (a String
) and a definition (also a String
). In this example, the word would be the key while the definition would be the value.
Section 13.3 (pp. 459-465) from the course textbook. You may skim over Section 13.3.2 (Downcasting) and ignore everything after Program 124 on page 465.
Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.
Map
.HashMap
object and assigns it to a Map
variable, both with and without using generics.put
method to add an entry into a given HashMap
object.get
method to retrieve a value from a given HashMap
object.List
and the Set
interfaces in Java.for-each
loop to print out all the keys/values in a given HashMap
.The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.
HashMap
to solve a problem.HashMap
.These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.
Reminder: You should test all of your solutions in DrJava.
What line of code would you write to import the Map
and HashMap
classes?
Write a Java statement that creates a HashMap
that maps a String
object to a Picture
object (i.e. a mapping between a title of a picture and the picture itself). Assign this new object to a Map
variable named gallery. You should utilize generics to explicitly set the types that are being used by the map (namely String
and Picture
).
Part A: Write Java code to create three new Picture
objects and add them to the gallery
map, using whatever titles you want.
Part B: Write Java code that uses the HashMap
class’ get
method to locate one of the items in your gallery. Assign the result of the get
method to a Picture
variable named foo
.
Write a for-each
loop that first prints out the title of each item in the gallery
map, and then displays the associated picture object using the show
method.