hashmap能夠用null爲鍵值

import java.util.HashMap;java

import  java.util.Map;
import  java.util.TreeMap;
 
public  class  TestMain {
     public  static  void  main(String[] args) {
 
         // HashMap能夠的鍵值能夠是null, "".
         Map<String, String> strMap1 = new  HashMap<String, String>();
         strMap1.put( null , "1" );
         strMap1.put( "" , "2" );
         strMap1.put( " " , "3" );
         strMap1.put( null , "4" );
         System.out.println(strMap1.get( null ));
         for  (String s : strMap1.keySet()) {
             System.out.println(s);
         }
         for  (String s : strMap1.values()) {
             System.out.println(s);
         }
         
         // TreeMap的鍵值不能是null
         Map<String, String> strMap2 = new  TreeMap<String, String>();
         strMap2.put( null , "1" );
         //strMap2.put("", "2");
         //strMap2.put(" ", "3");
         //strMap2.put(null, "4");
         //System.out.println(strMap2.get(null));
         for  (String s : strMap2.keySet()) {
             System.out.println(s);
         }
         for  (String s : strMap2.values()) {
             System.out.println(s);
         }
     }
}
相關文章
相關標籤/搜索