Chapter 10.3 – Java Maps | Introduction to Programming Using Java

Chapter 10.3 – Java Maps | Introduction to Programming Using Java

 

10.3  Java Maps

 

Chapter 10.3 Maps | Introduction to Programming Using Java

 

An array of N elements can be thought of as a way of associating some item with each of the integers 0, 1, …, N-1. If i is one of these integers, it’s possible to get the item associated with i, and it’s possible to put a new item in the i-th position. These “get” and “put” operations define what it means to be an array.

A map is a kind of generalized array. Like an array, a map is defined by “get” and “put” operations. But in a map, these operations are defined not for integers 0, 1, …, N-1, but for arbitrary objects of some specified type T. Associated to these objects of type T are objects of some possibly different type S.

In fact, some programming languages use the term associative array instead of “map” and use the same notation for associative arrays as for regular arrays. In those languages, for example, you might see the notation A[“fred”] used to indicate the item associated to the string “fred” in the associative array A.

Java does not use array notation for maps, unfortunately, but the idea is the same: A map is like an array, but the indices for a map are objects, not integers.

 

 

Chapter 10.3 Maps | Introduction to Programming Using Java

 

 

In a map, an object that serves as an “index” is called a key. The object that is associated with a key is called a value. Note that a key can have at most one associated value, but the same value can be associated to several different keys. A map can be considered to be a set of “associations,” where each association is a key/value pair.

 

 

The Map Interface

 

Chapter 10.3 - Java Maps | Introduction to Programming Using Java

 

In Java, maps are defined by the interface java.util.Map, which includes put and get methods as well as other general methods for working with maps. The map-interface, Map<T,S>, is parameterized by two types.

The first type parameter, T, specifies the type of objects that are possible keys in the map; the second type parameter, S, specifies the type of objects that are possible values in the map. For example, a map of type Map<Date,JButton> would associate values of type JButton to keys of type Date. For a map of type Map<String,String>, both the keys and the values are of type String.

 

Chapter 10.3 - Java Maps | Introduction to Programming Using Java

 

 

 

SEE MORE:

3 thoughts on “Chapter 10.3 – Java Maps | Introduction to Programming Using Java”

Leave a Comment