Java Entry類詳解


Entry類概述
Java的entry是一個靜態內部類,實現Map.Entry< K ,V> 這個接口,通過entry類可以構成一個單向鏈表。

一.java中Map及Map.Entry
(1).Map是java中的接口,Map.Entry是Map的一個內部接口。
(2).Map提供了一些常用方法,如keySet()、entrySet()等方法。
(3).keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一個Set集合,此集合的類型為Map.Entry。
(4).Map.Entry是Map聲明的一個內部接口,此接口為泛型,定義為Entry<K,V>。它表示Map中的一個實體(一個key-value對)。接口中有getKey(),getValue方法。

二.Entry類的實現源碼

//源碼
private static class Entry<K,V> implements Map.Entry<K,V> {
        int hash;
        final K key;
        V value;
        //next 可構成單向鏈表
        Entry<K,V> next;

        protected Entry(int hash, K key, V value, Entry<K,V> next) {
            this.hash = hash;
            this.key =  key;
            this.value = value;
            this.next = next;
        }

        protected Object clone() {
            return new Entry<>(hash, key, value,(next==null ? null : (Entry<K,V>) next.clone()));
        }

        // Map.Entry Ops
        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }

        public V setValue(V value) {
            if (value == null)
                throw new NullPointerException();

            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry)o;

            return key.equals(e.getKey()) && value.equals(e.getValue());
        }

        public int hashCode() {
            return hash ^ value.hashCode();
        }

        public String toString() {
            return key.toString()+"="+value.toString();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM