五.用LruCache来缓存Bitmap的初始化 LruCache<String, Bitmap>mLruCache;//获取手机最大内存 单位 kbintmaxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);//一般都将1/8设为LruCache的最大缓存intcacheSize = maxMemory / 8; mLruCache=newLruCache<String, Bitmap>(maxMemory / 8) {/...
map =newLinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor,true) {// (an anonymous inner class)privatestaticfinallongserialVersionUID=1;@OverrideprotectedbooleanremoveEldestEntry(Map.Entry<K, V> eldest){returnsize() > LRUCache.this.cacheSize; } }; }/** * Retrieves an entry from the...
LRU这个算法就是把最近一次使用时间离现在时间最远的数据删除掉,而实现LruCache将会频繁的执行插入、删除等操作,我们就会想到使用LinkedList,但是我们又要基于Key-Value来保存数据,这个时候我们就会想起HashMap,但是HashMap不能像linkedList那样保留数据的插入顺序,如果要使用HashMap的话可以使用它的一个子类LinkedHashMap。
今天来介绍一下容器类中的另一个哈希表———》LinkedHashMap。这是HashMap的关门弟子,直接继承了HashMap的衣钵,所以拥有HashMap的全部特性,并青出于蓝而胜于蓝,有着一些HashMap没有的特性。 接下来就一起来看看这个关门弟子到底有多大能耐
2.LinkedHashMapvsHashMap TheLinkedHashMapclass is very similar toHashMapin most aspects. However, the linked hash map is based on both hash table and linked list to enhance the functionality of hash map. It maintains a doubly-linked list running through all its entries in addition to an un...
以上代码展示了如何使用LinkedHashMap来实现一个简单的LRUCache。通过重写removeEldestEntry方法,我们可以在缓存满时自动移除最久未使用的条目,从而实现LRU缓存策略。
一句话解释:LruCache(least recently used cache)最近最少使用缓存。 前面,我们一起学习了LinkedHashMap数据结构,那么LruCache
// Create cache final int MAX_ENTRIES = 100; Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) { // This method is called just after a new entry has been added public boolean removeEldes ...
publicclassMain{publicstaticvoidmain(String[]args){// 创建一个容量为 3 的 LRU 缓存LRUCache<Integer,String>cache=newLRUCache<>(3);// 向缓存中插入数据cache.put(1,"A");cache.put(2,"B");cache.put(3,"C");// 打印缓存内容System.out.println(cache);// 输出: {1=A, 2=B, 3=C}//...
//在插入元素后调用,此方法可用于 LRUcache 算法中移除最近最少使用的元素 128 void afterNodeInsertion(boolean evict) { 129 LinkedHashMap.Entry<K,V> first; 130 if (evict && (first = head) != null && removeEldestEntry(first)) { 131 K key = first.key; 132 removeNode(hash(key), key...