HashIterator(){expectedModCount=modCount;if(size>0){// advance to first entryEntry[]t=table;while(index<t.length&&(next=t[index++])==null);}}finalEntry<K,V>nextEntry(){if(modCount!=expectedModCount)thrownewConcurrentModificationException();Entry<K,V>e=next;if(e==null)thrownewNoSuchElementException();if((next=e.next)==null){Entry[]t=table;while(index<t.length&&(next=t[index++])==null);}current=e;returne;}publicvoidremove(){if(current==null)thrownewIllegalStateException();if(modCount!=expectedModCount)thrownewConcurrentModificationException();Objectk=current.key;current=null;HashMap.this.removeEntryForKey(k);expectedModCount=modCount;}
publicclassHashSet<E>extendsAbstractSet<E>implementsSet<E>,Cloneable,java.io.Serializable{staticfinallongserialVersionUID=-5024744406713321676L;//使用HashMap的key保存HashSet中的所有元素privatetransientHashMap<E,Object>map;// Dummy value to associate with an Object in the backing Map//定义一个虚拟的Object对象作为HashMap的valueprivatestaticfinalObjectPRESENT=newObject();/** * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial capacity (16) and load factor (0.75). *///初始化HashSet,底层会初始化一个HashMappublicHashSet(){map=newHashMap<E,Object>();}//指定初始容量和loadfactor来初始化HashSet,其实就是初始化HashMap//loadfactor = 散列表的实际元素数目(n)/ 散列表的容量(m)publicHashSet(intinitialCapacity,floatloadFactor){map=newHashMap<E,Object>(initialCapacity,loadFactor);}/** * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * the specified initial capacity and default load factor (0.75). * * @param initialCapacity the initial capacity of the hash table * @throws IllegalArgumentException if the initial capacity is less * than zero */publicHashSet(intinitialCapacity){map=newHashMap<E,Object>(initialCapacity);}/** * Constructs a new, empty linked hash set. (This package private * constructor is only used by LinkedHashSet.) The backing * HashMap instance is a LinkedHashMap with the specified initial * capacity and the specified load factor. * * @param initialCapacity the initial capacity of the hash map * @param loadFactor the load factor of the hash map * @param dummy ignored (distinguishes this * constructor from other int, float constructor.) * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */HashSet(intinitialCapacity,floatloadFactor,booleandummy){map=newLinkedHashMap<E,Object>(initialCapacity,loadFactor);}/** * Returns an iterator over the elements in this set. The elements * are returned in no particular order. * * @return an Iterator over the elements in this set * @see ConcurrentModificationException *///调用Map的keyset来返回迭代器publicIterator<E>iterator(){returnmap.keySet().iterator();}/** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * this set contains no element <tt>e2</tt> such that * <tt>(e==null ? e2==null : e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element *///将e作为key插入了Hashmappublicbooleanadd(Ee){returnmap.put(e,PRESENT)==null;}/** * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements * themselves are not cloned. * * @return a shallow copy of this set *///拷贝通过两步完成:1、通过调用super.clone完成父类的拷贝;2、通过调用map.clone()完成对成员变量map的拷贝。注意map的拷贝也是调用super.clone完成,所以拷贝都是浅拷贝。另外需要注意拷贝过程会抛出CloneNotSupportedException异常,这是一个检查异常。publicObjectclone(){try{HashSet<E>newSet=(HashSet<E>)super.clone();newSet.map=(HashMap<E,Object>)map.clone();returnnewSet;}catch(CloneNotSupportedExceptione){thrownewInternalError();}}
(1) LRU缓存
我们用缓存来存放以前读取的数据,而不是直接丢掉,这样,再次读取的时候,可以直接在缓存里面取,而不用再重新查找一遍,这样系统的反应能力会有很大提高。但是,当我们读取的个数特别大的时候,我们不可能把所有已经读取的数据都放在缓存里,毕竟内存大小是一定的,我们一般把最近常读取的放在缓存里。
LRU缓存利用了这样的一种思想。LRU是Least Recently Used 的缩写,翻译过来就是“最近最少使用”,也就是说,LRU缓存把最近最少使用的数据移除,让给最新读取的数据。而往往最常读取的,也是读取次数最多的,所以,利用LRU缓存,我们能够提高系统的性能。
(2) 为什么是LinkedHashMap
第一,它的数据结构包含一个双向链表,其源代码片段如下:
123456789101112
publicclassLinkedHashMap<K,V>extendsHashMap<K,V>implementsMap<K,V>{/** * The head of the doubly linked list. */privatetransientEntry<K,V>header;其中Entry的定义的代码片段如下:/** * LinkedHashMap entry. */privatestaticclassEntry<K,V>extendsHashMap.Entry<K,V>{// These fields comprise the doubly linked list used for iteration. Entry<K,V>before,after;