《java集合》--EnumMap

《java集合》–EnumMap

說明:此文章基於jdk1.8

參考:

簡介

首先對比HashMap的實現,HashMap數據結構是數組散列,key值做hash運算後根據算法落在數組上,不同的hash值最後可能落在同一個桶上,在一個桶上的多個entry對象使用鏈表存儲,當數組沒有鏈表存在時,HashMap性能最好爲O(1)。而最差爲O(threshould)即所有元素存在一個鏈表上

當枚舉作爲key存入map的情況,由於枚舉值得個數是一定得,那麼直接創建一個枚舉值個數大小的數組用於存儲,Enum性能爲O(1)

所有的枚舉類都繼承自java.lang.Enum,根據ordinal()方法獲取枚舉實例的序號,然後去values數組中操作該下標處的value。

數據結構

EnumMap的存儲結構是一個數組,數組中存儲了value值,長度等於枚舉實例的個數,根據枚舉實例在枚舉類中的ordinal去操作數組對應下標的value值

image

基本屬性

  • private final Class keyType;// 枚舉類型
  • private transient K[] keyUniverse; //枚舉類型的values
  • private transient Object[] vals; //EnumMap中存放的value值

構造器

創建EnumMap時傳入Enum枚舉的具體類型,EnumMap會根據枚舉的values的size創建一個size大小的數組

public EnumMap(Class<K> keyType) {
  this.keyType = keyType;
  //獲取枚舉類型的所有value
  keyUniverse = getKeyUniverse(keyType);
  //根據values的size創建數組
  vals = new Object[keyUniverse.length];
}
public EnumMap(EnumMap1<K, ? extends V> m) {
  keyType = m.keyType;
  keyUniverse = m.keyUniverse;
  vals = m.vals.clone();
  size = m.size;
}
public EnumMap(Map<K, ? extends V> m) {
  if (m instanceof EnumMap1) {
    EnumMap1<K, ? extends V> em = (EnumMap1<K, ? extends V>) m;
    keyType = em.keyType;
    keyUniverse = em.keyUniverse;
    vals = em.vals.clone();
    size = em.size;
  } else {
    if (m.isEmpty())
      throw new IllegalArgumentException("Specified map is empty");
    keyType = m.keySet().iterator().next().getDeclaringClass();
    keyUniverse = getKeyUniverse(keyType);
    vals = new Object[keyUniverse.length];
    putAll(m);
  }
}

添加元素

根據key值獲取枚舉的ordinal下標,直接向數組位置添加value

public V put(K key, V value) {
  //驗證枚舉類型是否合法
  typeCheck(key);
  //獲取枚舉值在枚舉類中的下標
  int index = key.ordinal();
  //從數組中獲取對應下標的值
  Object oldValue = vals[index];
  //數組下標處賦值
  vals[index] = maskNull(value);
  //如果第一次加入 size+1
  if (oldValue == null)
    size++;
  return unmaskNull(oldValue);
}
private void typeCheck(K key) {
  Class<?> keyClass = key.getClass();
  if (keyClass != keyType && keyClass.getSuperclass() != keyType)
    throw new ClassCastException(keyClass + " != " + keyType);
}
//處理空值
private Object maskNull(Object value) {
  return (value == null ? NULL : value);
}
//處理空值
private V unmaskNull(Object value) {
  return (V)(value == NULL ? null : value);
}
//put的時候直接根據key獲取ordinal,然後修改數組該下標處的值
public V put(K key, V value) {
  typeCheck(key);
  int index = key.ordinal();
  Object oldValue = vals[index];
  vals[index] = maskNull(value);
  if (oldValue == null)
    size++;
  return unmaskNull(oldValue);
}

刪除元素

獲取到key值得下標,然後操作數組處指向null

public V remove(Object key) {
  if (!isValidKey(key))
    return null;
  int index = ((Enum<?>)key).ordinal();
  Object oldValue = vals[index];
  vals[index] = null;
  if (oldValue != null)
    size--;
  return unmaskNull(oldValue);
}
public void clear() {
  Arrays.fill(vals, null);
  size = 0;
}

獲取元素

直接根據枚舉值在枚舉中的下標從value數組中獲取,ordinal

public V get(Object key) {
  return (isValidKey(key) ?
          unmaskNull(vals[((Enum<?>)key).ordinal()]) : null);
}
//驗證key值是否合法
private boolean isValidKey(Object key) {
  if (key == null)
    return false;

  // Cheaper than instanceof Enum followed by getDeclaringClass
  Class<?> keyClass = key.getClass();
  return keyClass == keyType || keyClass.getSuperclass() == keyType;
}

遍歷

只需要遍歷數組,O(n)級別

//遍歷value
public boolean containsValue(Object value) {
  value = maskNull(value);
  for (Object val : vals)
    if (value.equals(val))
      return true;

  return false;
}
//遍歷key 
public boolean containsKey(Object key) {
  return isValidKey(key) && vals[((Enum<?>)key).ordinal()] != null;
}
//迭代器
private abstract class EnumMapIterator<T> implements Iterator<T> {
        // Lower bound on index of next element to return
        int index = 0;

        // Index of last returned element, or -1 if none
        int lastReturnedIndex = -1;

        public boolean hasNext() {
            while (index < vals.length && vals[index] == null)
                index++;
            return index != vals.length;
        }

        public void remove() {
            checkLastReturnedIndex();

            if (vals[lastReturnedIndex] != null) {
                vals[lastReturnedIndex] = null;
                size--;
            }
            lastReturnedIndex = -1;
        }

        private void checkLastReturnedIndex() {
            if (lastReturnedIndex < 0)
                throw new IllegalStateException();
        }
    }

    private class KeyIterator extends EnumMapIterator<K> {
        public K next() {
            if (!hasNext())
                throw new NoSuchElementException();
            lastReturnedIndex = index++;
            return keyUniverse[lastReturnedIndex];
        }
    }

    private class ValueIterator extends EnumMapIterator<V> {
        public V next() {
            if (!hasNext())
                throw new NoSuchElementException();
            lastReturnedIndex = index++;
            return unmaskNull(vals[lastReturnedIndex]);
        }
    }

    private class EntryIterator extends EnumMapIterator<Map.Entry<K,V>> {
        private Entry lastReturnedEntry;

        public Map.Entry<K,V> next() {
            if (!hasNext())
                throw new NoSuchElementException();
            lastReturnedEntry = new Entry(index++);
            return lastReturnedEntry;
        }

        public void remove() {
            lastReturnedIndex =
                ((null == lastReturnedEntry) ? -1 : lastReturnedEntry.index);
            super.remove();
            lastReturnedEntry.index = lastReturnedIndex;
            lastReturnedEntry = null;
        }

        private class Entry implements Map.Entry<K,V> {
            private int index;

            private Entry(int index) {
                this.index = index;
            }

            public K getKey() {
                checkIndexForEntryUse();
                return keyUniverse[index];
            }

            public V getValue() {
                checkIndexForEntryUse();
                return unmaskNull(vals[index]);
            }

            public V setValue(V value) {
                checkIndexForEntryUse();
                V oldValue = unmaskNull(vals[index]);
                vals[index] = maskNull(value);
                return oldValue;
            }

            public boolean equals(Object o) {
                if (index < 0)
                    return o == this;

                if (!(o instanceof Map.Entry))
                    return false;

                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                V ourValue = unmaskNull(vals[index]);
                Object hisValue = e.getValue();
                return (e.getKey() == keyUniverse[index] &&
                        (ourValue == hisValue ||
                         (ourValue != null && ourValue.equals(hisValue))));
            }

            public int hashCode() {
                if (index < 0)
                    return super.hashCode();

                return entryHashCode(index);
            }

            public String toString() {
                if (index < 0)
                    return super.toString();

                return keyUniverse[index] + "="
                    + unmaskNull(vals[index]);
            }

            private void checkIndexForEntryUse() {
                if (index < 0)
                    throw new IllegalStateException("Entry was removed");
            }
        }
    }

總結

  • 當key值是枚舉類型的時候,使用EnumMap存儲,會提高性能
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章