The basic operations (put
,get
,remove
,containsKey
,containsValue
,size
, andisEmpty
) behave exactly like their counterparts inHashtable
. Here's a simple program to generate a frequency table of the words found in its argument list. The frequency table maps each word to the number of times it occurs in the argument list.The only thing even slightly tricky about this program is the second argument of theimport java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size()+" distinct words detected:"); System.out.println(m); } }put
statement. It's a conditional expression that has the effect of setting the frequency to one if the word has never been seen before, or one more than its current value if the word has already been seen. Let's run the program:Suppose you'd prefer to see the frequency table in alphabetical order. All you have to do is change the implementation type of the% java Freq if it is to be it is up to me to delegate 8 distinct words detected: {to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1}Map
fromHashMap
toTreeMap
. Making this four character change causes the program to generate the following output from the same command line:Are interfaces cool, or what? Like the8 distinct words detected: {be=1, delegate=1, if=1, is=2, it=2, me=1, to=3, up=1}Set
andList
interfaces,Map
strengthens the requirements on theequals
andhashCode
methods so that twoMap
objects can be compared for logical equality without regard to their implementation types. TwoMap
objects are equal if they represent the same key-value mappings.
By convention, allMap
implementations provide constructors that take aMap
object and initialize the newMap
to contain all of the key-value mappings in the specifiedMap
. This standardMap
constructor is entirely analogous to the standard collection constructor forCollection
implementations. It allows the caller to create aMap
of a desired implementation type that initially contains all of the mappings in anotherMap
, regardless of the otherMap
's implementation type. For example, suppose you have aMap
, namedm
. The following one-liner creates a newHashMap
initially containing all of the same key-value mappings asm
:
Map copy = new HashMap(m);
A java blog with a collection of examples and tutorials on Java and related technologies. (Under maintenance with continuous updates) Be in touch with java jazzle or k2java.blogspot.com.
Sunday, March 13, 2011
Basic Operations in map
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment