Java Reference
In-Depth Information
Class
Representation
Since
Random
access
Notes
Array
1.0
Yes
Extends Vector ; adds push() , pop() ,
peek() . Legacy; use Deque instead.
Stack
The Map Interface
A map is a set of key objects and a mapping from each member of that set to a value
object. The Map interface defines an API for defining and querying mappings. Map is
part of the Java Collections Framework, but it does not extend the Collection
interface, so a Map is a little-c collection, not a big-C Collection . Map is a parame‐
terized type with two type variables. Type variable K represents the type of keys held
by the map, and type variable V represents the type of the values that the keys are
mapped to. A mapping from String keys to Integer values, for example, can be
represented with a Map<String,Integer> .
The most important Map methods are put() , which defines a key/value pair in the
map, get() , which queries the value associated with a specified key, and remove() ,
which removes the specified key and its associated value from the map. The general
performance expectation for Map implementations is that these three basic methods
are quite efficient: they should usually run in constant time and certainly no worse
than in logarithmic time.
An important feature of Map is its support for “collection views.” A Map is not a Col
lection , but its keys can be viewed as a Set , its values can be viewed as a Collec
tion , and its mappings can be viewed as a Set of Map.Entry objects. ( Map.Entry is a
nested interface defined within Map : it simply represents a single key/value pair.)
The following sample code shows the get() , put() , remove() , and other methods
of a Map and also demonstrates some common uses of the collection views of a Map :
// New, empty map
Map < String , Integer > m = new HashMap ();
// Immutable Map containing a single key-value pair
Map < String , Integer > singleton = Collections . singletonMap ( "test" , - 1 );
// Note this rarely used syntax to explicitly specify the parameter
// types of the generic emptyMap method. The returned map is immutable
Map < String , Integer > empty = Collections .< String , Integer > emptyMap ();
s
a
// Populate the map using the put method to define mappings
// from array elements to the index at which each element appears
String [] words = { "this" , "is" , "a" , "test" };
for ( int i = 0 ; i < words . length ; i ++) {
m . put ( words [ i ], i ); // Note autoboxing of int to Integer
}
 
Search WWH ::




Custom Search