首頁 Java java教程 Java集合之Map的範例程式碼詳解

Java集合之Map的範例程式碼詳解

Mar 13, 2017 pm 05:42 PM

Map架構



#如上圖:

(1)Map是映射介面,Map中儲存的內容是鍵值對(key-value)

(2)AbstractMap是繼承於Map的抽象類別,實作了Map中的大部分API

(3)SortedMap是繼承於Map的接口,SortedMap中的內容是排序的鍵值對,排序的方法是透過比較器。

(4)NavigableMap繼承於SortedMap,其中有一系列的導航方法,例如「取得大於或等於某物件的鍵值對」等等

(5 )TreeMap繼承於AbstractMap和NavigableMap接口,因此TreeMap中的內容是有序的鍵值對。

(6)HashMap繼承於AbstractMap,內容也是鍵值對,但不保證順序。

(7)WeakHashMap繼承於AbstractMap,它和HashMap的鍵類型不同,WeakHashMap是弱鍵。

(8)HashTable繼承於Directionary同時也實作了Map,因此是鍵值對的,但不保證次序,同時是執行緒安全的。

總結:

HashMap是基於」拉鍊法「實現的散列表,一般用於單線程,鍵值都可以為空,支援Iterator(迭代器)遍歷

Hashtable是基於」拉鍊法「實現的散列表,是線程安全的,可以用於多執行緒程式中。支援Iterator(迭代器)遍歷和Enumeration(枚舉器)兩種遍歷方式。

WeakHashMap也是基於」拉鍊法「實現的散列表,同時是弱鍵

TreeMap 是有序的散列表,透過紅黑樹來實現的,鍵值都不能為空。


Java8的Map介面的原始碼:

<p>public interface Map<K,V> {<br>    int size();//数目<br>    boolean isEmpty();//判断是否为空<br>    boolean containsKey(<a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a> key);//判断是否含有某个key<br>    boolean containsValue(Object value);//判断是否含有某个值<br>    V get(Object key);//通过key获得value<br>    V put(K key, V value);//插入键值对<br>    V remove(Object key);//通过key<a href="http://www.php.cn/php/php-tp-remove.html" target="_blank">删除</a><br>    void put<a href="http://www.php.cn/wiki/1483.html" target="_blank">All</a>(Map<? <a href="http://www.php.cn/wiki/166.html" target="_blank">extends</a> K, ? extends V> m);//将一个Map插入<br>    void <a href="http://www.php.cn/wiki/917.html" target="_blank">clear</a>();//清空<br>    <a href="http://www.php.cn/code/8209.html" target="_blank">Set</a><K> keySet();//返回key集合<br>    Collection<V> values();//返回value<br>    Set<Map.Entry<K, V>> entrySet();//实体集合,Map的改变会影响到它<br>    interface Entry<K,V> {<br>        K getKey();//获得key<br>        V getValue();//获得value<br>        V setValue(V value);//设置值<br>        boolean equals(Object o);//判断对象是否相等<br>        int hashCode();//返回hashCode<br>        //比较器,比较两个key<br>        public <a href="http://www.php.cn/wiki/188.html" target="_blank">static</a> <K extends Comparable<? <a href="http://www.php.cn/code/8202.html" target="_blank">super</a> K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {<br>            <a href="http://www.php.cn/wiki/135.html" target="_blank">return</a> (Comparator<Map.Entry<K, V>> & Serializable)<br>                    (c1, c2) -> c1.getKey().compareTo(c2.getKey());<br>        }<br>        //比较两个值<br>        public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {<br>            return (Comparator<Map.Entry<K, V>> & Serializable)<br>                    (c1, c2) -> c1.getValue().compareTo(c2.getValue());<br>        }<br>        //比较两个key<br>        public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {<br>            Objects.<a href="http://www.php.cn/wiki/136.html" target="_blank">require</a>Non<a href="http://www.php.cn/wiki/62.html" target="_blank">Null</a>(cmp);<br>            return (Comparator<Map.Entry<K, V>> & Serializable)<br>                    (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());<br>        }<br>        //比较两个值<br>        public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {<br>            Objects.requireNonNull(cmp);<br>            return (Comparator<Map.Entry<K, V>> & Serializable)<br>                    (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());<br>        }<br>    }<br>    //比较map是否相等<br>    boolean equals(Object o);<br>    int hashCode();//hashCode<br>    default V get<a href="http://www.php.cn/wiki/1360.html" target="_blank">OrD</a>efault(Object key, V defaultValue) {<br>        V v;<br>        return (((v = get(key)) != null) || containsKey(key))<br>                ? v<br>                : defaultValue;<br>    }<br>    default void <a href="http://www.php.cn/wiki/127.html" target="_blank">forEach</a>(BiConsumer<? super K, ? super V> <a href="http://www.php.cn/java/java-Action.html" target="_blank">action</a>) {<br>        Objects.requireNonNull(action);<br>        for (Map.Entry<K, V> entry : entrySet()) {<br>            K k;<br>            V v;<br>            try {<br>                k = entry.getKey();<br>                v = entry.getValue();<br>            } catch(IllegalState<a href="http://www.php.cn/wiki/265.html" target="_blank">Exception</a> ise) {<br>                // this usually means the entry is no longer in the map.<br>                throw <a href="http://www.php.cn/wiki/165.html" target="_blank">new</a> Con<a href="http://www.php.cn/wiki/1046.html" target="_blank">current</a>Mod<a href="http://www.php.cn/wiki/109.html" target="_blank">if</a>icationException(ise);<br>            }<br>            action.accept(k, v);<br>        }<br>    }<br>    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {<br>        Objects.requireNonNull(function);<br>        for (Map.Entry<K, V> entry : entrySet()) {<br>            K k;<br>            V v;<br>            try {<br>                k = entry.getKey();<br>                v = entry.getValue();<br>            } catch(IllegalStateException ise) {<br>                // this usually means the entry is no longer in the map.<br>                throw new ConcurrentModificationException(ise);<br>            }<br><br>            // ise thrown from function is not a cme.<br>            v = function.apply(k, v);<br><br>            try {<br>                entry.setValue(v);<br>            } catch(IllegalStateException ise) {<br>                // this usually means the entry is no longer in the map.<br>                throw new ConcurrentModificationException(ise);<br>            }<br>        }<br>    }<br>    default V putIfAbsent(K key, V value) {<br>        V v = get(key);<br>        if (v == null) {<br>            v = put(key, value);<br>        }<br><br>        return v;<br>    }<br>    //删除某个key和value对应的对象<br>    default boolean remove(Object key, Object value) {<br>        Object curValue = get(key);<br>        if (!Objects.equals(curValue, value) ||<br>                (curValue == null && !containsKey(key))) {<br>            return false;<br>        }<br>        remove(key);<br>        return true;<br>    }<br>    //将某个key和oldValue对应的值替换为newValue<br>    default boolean replace(K key, V oldValue, V newValue) {<br>        Object curValue = get(key);<br>        if (!Objects.equals(curValue, oldValue) ||<br>                (curValue == null && !containsKey(key))) {<br>            return false;<br>        }<br>        put(key, newValue);<br>        return true;<br>    }<br>    //替换key的值<br>    default V replace(K key, V value) {<br>        V curValue;<br>        if (((curValue = get(key)) != null) || containsKey(key)) {<br>            curValue = put(key, value);<br>        }<br>        return curValue;<br>    }<br>    default V computeIfAbsent(K key,<br>                              Function<? super K, ? extends V> mappingFunction) {<br>        Objects.requireNonNull(mappingFunction);<br>        V v;<br>        if ((v = get(key)) == null) {<br>            V newValue;<br>            if ((newValue = mappingFunction.apply(key)) != null) {<br>                put(key, newValue);<br>                return newValue;<br>            }<br>        }<br><br>        return v;<br>    }<br>    default V computeIfPresent(K key,<br>                               BiFunction<? super K, ? super V, ? extends V> remappingFunction) {<br>        Objects.requireNonNull(remappingFunction);<br>        V oldValue;<br>        if ((oldValue = get(key)) != null) {<br>            V newValue = remappingFunction.apply(key, oldValue);<br>            if (newValue != null) {<br>                put(key, newValue);<br>                return newValue;<br>            } <a href="http://www.php.cn/wiki/111.html" target="_blank">else</a> {<br>                remove(key);<br>                return null;<br>            }<br>        } else {<br>            return null;<br>        }<br>    }<br>    default V compute(K key,<br>                      BiFunction<? super K, ? super V, ? extends V> remappingFunction) {<br>        Objects.requireNonNull(remappingFunction);<br>        V oldValue = get(key);<br><br>        V newValue = remappingFunction.apply(key, oldValue);<br>        if (newValue == null) {<br>            // <a href="http://www.php.cn/wiki/1298.html" target="_blank">delete</a> mapping<br>            if (oldValue != null || containsKey(key)) {<br>                // something to remove<br>                remove(key);<br>                return null;<br>            } else {<br>                // nothing to do. Leave things as they were.<br>                return null;<br>            }<br>        } else {<br>            // add or replace old mapping<br>            put(key, newValue);<br>            return newValue;<br>        }<br>    }<br>    default V merge(K key, V value,<br>                    BiFunction<? super V, ? super V, ? extends V> remappingFunction) {<br>        Objects.requireNonNull(remappingFunction);<br>        Objects.requireNonNull(value);<br>        V oldValue = get(key);<br>        V newValue = (oldValue == null) ? value :<br>                remappingFunction.apply(oldValue, value);<br>        if(newValue == null) {<br>            remove(key);<br>        } else {<br>            put(key, newValue);<br>        }<br>        return newValue;<br>    }<br>}<br></p>
登入後複製

以上是Java集合之Map的範例程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Java Spring 面試題 Java Spring 面試題 Aug 30, 2024 pm 04:29 PM

在本文中,我們保留了最常被問到的 Java Spring 面試問題及其詳細答案。這樣你就可以順利通過面試。

突破或從Java 8流返回? 突破或從Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP與Python:了解差異 PHP與Python:了解差異 Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

Java程序查找膠囊的體積 Java程序查找膠囊的體積 Feb 07, 2025 am 11:37 AM

膠囊是一種三維幾何圖形,由一個圓柱體和兩端各一個半球體組成。膠囊的體積可以通過將圓柱體的體積和兩端半球體的體積相加來計算。本教程將討論如何使用不同的方法在Java中計算給定膠囊的體積。 膠囊體積公式 膠囊體積的公式如下: 膠囊體積 = 圓柱體體積 兩個半球體體積 其中, r: 半球體的半徑。 h: 圓柱體的高度(不包括半球體)。 例子 1 輸入 半徑 = 5 單位 高度 = 10 單位 輸出 體積 = 1570.8 立方單位 解釋 使用公式計算體積: 體積 = π × r2 × h (4

PHP與Python:核心功能 PHP與Python:核心功能 Apr 13, 2025 am 12:16 AM

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

創造未來:零基礎的 Java 編程 創造未來:零基礎的 Java 編程 Oct 13, 2024 pm 01:32 PM

Java是熱門程式語言,適合初學者和經驗豐富的開發者學習。本教學從基礎概念出發,逐步深入解說進階主題。安裝Java開發工具包後,可透過建立簡單的「Hello,World!」程式來實踐程式設計。理解程式碼後,使用命令提示字元編譯並執行程序,控制台上將輸出「Hello,World!」。學習Java開啟了程式設計之旅,隨著掌握程度加深,可創建更複雜的應用程式。

See all articles