java 入土--集合詳解( 三 )


實際開發中,常用 HashMap,TreeMap,LinkedHAshMap,和 HashTable 的子類 properties 。
Map 集合的方法
Map<String, String> map = new HashMap<String, String>();//put方法添加元素map.put("01","maoyaning");map.put("02","guojing");//remove方法刪除元素map.remove("01");//clear方法移除所有元素map.clear();//containsKey方法判斷是否包含指定的鍵System.out.println(map.containsKey("01"));//containsValue方法判斷是否含有指定的值System.out.println(map.containsValue("maoyaning"));//size返回集合的鍵值對個數System.out.println(map.size());//isEmpty判斷集合是否為空System.out.println(map.isEmpty());Map 集合的獲取功能
Map<String, String> map = new HashMap<String, String>();map.put("zhangwuji","01");map.put("asdf","dsf");//get方法,根據鍵,返回值單個值System.out.println(map.get("zhangwuji"));//keySet獲取所有鍵的集合Set<String> keySet = map.keySet();//獲取key的Set集合//增強for循環迭代獲取key值for (String key : keySet) {System.out.println(map.get(key));}//values獲取所有值的集合Collection<String> values = map.values();for (String value : values) {System.out.println(value);}/**在創建 Map 集合時,Map 的底層會創建 EntrySet 集合,用于存放 Entry 對象,而一個 Entry 對象具有 key 和 value , 同時創建 Set 數組指向 key,創建 collection 對象指向 value,取出時,實際上是調用 set 和 collection 數組的地址進行調用,從而提高遍歷效率 。*/Map 集合的遍歷
//方法一Map<String, String> map = new HashMap<String, String>();map.put("01","mao");map.put("02","ya");//Map集合的遍歷方法//獲取所有鍵的集合 , 用KeySet方法實現Set<String> set = map.keySet();//遍歷每一個鍵for (String key : set) {//根據鍵找到值String value = https://www.huyubaike.com/biancheng/map.get(key);System.out.println(value);}//方法二//通過entryset方法獲得鍵值對集合//獲取所有鍵值對對象的集合Set> entries = map.entrySet();//遍歷鍵值對對象集合 , 得到每一個鍵值對對象for (Map.Entry entry : entries) {System.out.println(entry.getKey());System.out.println(entry.getValue());}//方法三Set> entries = map.entrySet();Iterator iterator = entries.iterator();while (iterator.hasNext()) {Map.Entry next = iterator.next();System.out.println(next.getKey()+next.getValue());}【java 入土--集合詳解】

推薦閱讀