目录
Map 接口
1. 特性描述
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.Map集合是将键映射到值的对象。 映射不能包含重复的键:每个键最多可以映射到一个值。The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.Java平台包含三个常用 Map 的实现: HashMap , TreeMap 和 LinkedHashMap 。
Map 接口常用方法
int size (); // 获取集合的大小boolean isEmpty (); // 判断集合是否为空boolean containsKey ( Object key ); // 判断集合中是否包含给定的键boolean containsValue ( Object value ); // 判断集合中是否包含给定的值V get ( Object key ); // 获取集合中给定键对应的值V put ( K key , V value ); // 将一个键值对放入集合中V remove ( Object key ); // 将给定的键从集合中移除void putAll ( Map <? extends K , ? extends V > m ); // 将给定的集合添加到集合中void clear (); // 清除集合中所有元素Set < K > keySet (); // 获取集合中键的集合Collection < V > values (); // 获取集合中值的集合Set < Map . Entry < K , V >> entrySet (); // 获取集合中键值对的集合
Entry 接口常用方法
K getKey (); // 获取键V getValue (); // 获取值V setValue ( V value ); // 设置值boolean equals ( Object o ); // 比较是否是同一个对象int hashCode (); // 获取哈希码
Map
接口中的内部接口
Entry
就是
map
存储的数据项,一个
Entry
就是一个键值对
package com . wq . map ;public class MyEntry < K , V > {private K key ;private V value ;private MyEntry < K , V > next ;public MyEntry ( K key , V value , MyEntry < K , V > next ) {this . key = key ;this . value = value ;this . next = next ;}public MyEntry < K , V > getNext () {return next ;}public void setNext ( MyEntry < K , V > next ) {this . next = next ;}public K getKey () {return key ;}public void setKey ( K key ) {this . key = key ;}public V getValue () {return value ;}public void setValue ( V value ) {this . value = value ;}}package com . wq . map ;public class MyMap < K , V > {private MyEntry < K , V > [] elements ;private int size ;private float loadFactor = 0.75f ; // 负载因子public MyMap () {this ( 16 );}public MyMap ( int capacity ) {this . elements = new MyEntry [ capacity ];}public V put ( K key , V value ){int currentSize = size + 1 ;if ( currentSize >= elements . length * loadFactor ){MyEntry < K , V > [] entries = new MyEntry [ currentSize << 1 ];for ( MyEntry < K , V > entry : entries ){int hash = entry . getKey (). hashCode ();int index = hash & ( entries . length - 1 );entries [ index ] = entry ;}elements = entries ;}int hash = key . hashCode ();int index = hash & ( elements . length - 1 );MyEntry < K , V > addEntry = new MyEntry <> ( key , value , null );if ( elements [ index ] == null ){elements [ index ] = addEntry ;} else {MyEntry < K , V > existEntry = elements [ index ];while ( existEntry . getNext () != null ){existEntry = existEntry . getNext ();}existEntry . setNext ( addEntry );}size ++ ;return elements [ index ]. getValue ();}public V get ( K key ){for ( MyEntry < K , V > entry : elements ){if ( entry == null ) continue ;K k = entry . getKey ();if ( k . equals ( key )) return entry . getValue ();MyEntry < K , V > temp = entry . getNext ();while ( temp != null ){if ( temp . getKey (). equals ( key )) return temp . getValue ();temp = temp . getNext ();}}return null ;}public int size (){return size ;}public boolean isEmpty (){return size == 0 ;}}package com . wq . map ;public class Test {public static void main ( String [] args ) {MyMap < Integer , String > map = new MyMap <> ();map . put ( 1 , "a" );map . put ( 2 , "b" );map . put ( 3 , "c" );map . put ( 17 , "d" );map . put ( 33 , "e" );}}
2. HashMap
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.基于哈希表的Map 接口的实现。此实现提供所有可选的映射操作,并允许空值和空键。( HashMap 类与 Hashtable大致等效,不同之处在于它是不同步的,并且允许为 null 。)该类不保证映射的顺序。 特别是,它不能保证顺序会随着时间的推移保持恒定。
HashMap 存储的是一组无序的键值对。存储时是根据键的哈希码来计算存储的位置,因为对象的哈希码是不确定的,因此 HashMap
存储的元素是无序的。
示例及源码解读
package com . wq . map ;import java . util . * ;public class HashMapTest {public static void main ( String [] args ) {//HashMap采用的是数组、链表以及红黑树来存储数据。//链表的设计主要是针对于Hash 碰撞而引发存储位置冲突//红黑树的设计主要是针对于链表过长,遍历速度太慢HashMap < Integer , String > map = new HashMap <> ();map . put ( 1 , "a" );map . put ( 2 , "b" );map . put ( 3 , "c" );map . put ( 4 , "d" );map . put ( 17 , "e" );String value = map . get ( 1 );System . out . println ( value );System . out . println ( map . size ());System . out . println ( map . isEmpty ());System . out . println ( map . containsKey ( 3 ));System . out . println ( map . containsValue ( "e" ));System . out . println ( map . remove ( 17 ));HashMap < Integer , String > map1 = new HashMap <> ();map1 . put ( 5 , "CN" );map1 . put ( 6 , "US" );map1 . put ( 7 , "EN" );map . putAll ( map1 );System . out . println ( map . size ());Set < Integer > keySet = map . keySet ();for ( Integer i : keySet ){System . out . println ( i );}System . out . println ( "=============" );Collection < String > values = map . values ();for ( String str : values ){System . out . println ( str );}System . out . println ( "=============" );Set < Map . Entry < Integer , String >> entries = map . entrySet ();for ( Map . Entry < Integer , String > entry : entries ){Integer key = entry . getKey ();String val = entry . getValue ();System . out . println ( key + "=>" + val );}System . out . println ( "=============" );map . clear ();System . out . println ( map . size ());}}
HashMap
采用的是数组加单向链表加红黑树的组合来存储数据。
3. TreeMap
A Red - Black tree based NavigableMap implementation . The map is sorted according to the natural ordering of its keys , or by a Comparator provided at map creation time , depending on which constructor is used .基于红黑树的NavigableMap 实现。根据集合存储的键的自然排序或在映射创建时提供的 Comparator 来对键进行排序,具体取决于所使用的构造方法。
示例及源码解读
package com . wq . map ;import java . util . Comparator ;import java . util . Set ;import java . util . TreeMap ;public class TreeMapTest {public static void main ( String [] args ) {Comparator < Computer > c = ( o1 , o2 ) -> Double . compare ( o1 . getPrice (),o2 . getPrice ());TreeMap < Computer , Integer > map1 = new TreeMap <> ( c );map1 . put ( new Computer ( " 联想 " , 3000 ), 1 );map1 . put ( new Computer ( " 外星人 " , 30000 ), 2 );Set < Computer > set = map1 . keySet ();for ( Computer comp : set ){System . out . println ( comp );}}}
4. LinkedHashMap
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.Map接口的哈希表和链表实现,具有可预测的迭代顺序。 此实现与 HashMap 的不同之处在于,它维护一个贯穿其所有条目的双向链表。 此链表定义了迭代顺序,通常是将键插入映射的顺序(插入顺序)。 请注意,如果将键重新插入到映射中,则插入顺序不会受到影响。
示例及源码解读
package com . wq . map ;import java . util . LinkedHashMap ;import java . util . Map ;public class LinkedHashMapTest {public static void main ( String [] args ) {LinkedHashMap < String , String > map = new LinkedHashMap <> ();map . put ( "CN" , " 中华人名共和国 " ); // 第一次是放入map . put ( "EN" , " 英国 " );map . put ( "US" , " 美国 " );map . put ( "AU" , " 澳大利亚 " );map . put ( "CN" , " 中国 " ); // 第二次是修改for ( String key : map . keySet ()){System . out . println ( key );}for ( Map . Entry < String , String > entry : map . entrySet ()){System . out . println ( entry . getKey () + "=>" + entry . getValue ());}}}