Source:
1 PackageTest_demo;2 3 ImportJava.util.HashMap;4 ImportJava.util.Iterator;5 ImportJava.util.Map;6 ImportJava.util.Random;7 8 /*9 * @desc hashmap test programTen */ One A Public classHashmapdemo { - Private Static voidTesthashmapapis () { - //Initialize random seed theRandom r =NewRandom (); - //New HashMap -HashMap map =NewHashMap (); - //Add Action +Map.put ("One", R.nextint (10)); -Map.put ("I", R.nextint (10)); +Map.put ("Three", R.nextint (10)); A //print out a map atSYSTEM.OUT.PRINTLN ("Map:" +map); - //Traverse Key-value via iterator -Iterator iter =Map.entryset (). iterator (); - while(Iter.hasnext ()) { -Map.entry Entry =(Map.entry) Iter.next (); -System.out.println ("Next:" + entry.getkey () + ":" +Entry.getvalue ()); in } - //hashmap number of key-value pairs toSYSTEM.OUT.PRINTLN ("Size:" +map.size ()); + //ContainsKey (Object key): Contains key -System.out.println ("contains key:" + Map.containskey (")); theSystem.out.println ("contains key five:" + Map.containskey ("five")); * //Containsvalue (Object value): Whether the value is inclusive $System.out.println ("contains value 0:" + map.containsvalue (NewInteger (0)));Panax Notoginseng //Remove (Object key): Key value pair corresponding to key key -Map.Remove ("three"); theSystem.out.println ("Delete three"); +SYSTEM.OUT.PRINTLN ("Map:" +map); A //Clear (): Empty HashMap the map.clear (); +System.out.println ("Empty HashMap"); - //isEmpty (): HashMap is empty $System.out.println (Map.isempty ()? "Map is empty": "Map is not empty")); $ } - - Public Static voidMain (string[] args) { the Testhashmapapis (); - }Wuyi}
Execution Result:
Map:{one=1, Two=9, Three=2}next: one:1next: two:9next: Three:2size:3contains key Two:truecontains key F Ive:falsecontains value 0:false Delete threemap:{one=1, two=9} empty Hashmapmap is empty
HashMap usage of Java