Skip to content

Instantly share code, notes, and snippets.

@yoshi389111
Last active April 18, 2022 02:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshi389111/ca0594f803d24103077a to your computer and use it in GitHub Desktop.
Save yoshi389111/ca0594f803d24103077a to your computer and use it in GitHub Desktop.
LRU cache map
/*
* LruCacheMap.java
* Copyright (C) 2015, SATO_Yoshiyuki
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
import java.util.LinkedHashMap;
import java.util.Map;
/**
* LRUキャッシュマップ
*
* @author yoshi389111
*
* @param <K> キーの型
* @param <V> 値の型
*/
public class LruCacheMap<K, V> extends LinkedHashMap<K, V> {
/** シリアライズバージョン */
private static final long serialVersionUID = 1L;
/** 負荷係数 */
private static final float LOAD_FACTOR = 0.75f;
/** キャッシュエントリ最大数 */
private final int maxSize;
/**
* 指定された最大数でインスタンスを生成
*
* @param maxSize 最大数
*/
public LruCacheMap(int maxSize) {
super((int) Math.ceil(maxSize / LOAD_FACTOR) + 1, LOAD_FACTOR, true);
this.maxSize = maxSize;
}
/**
* エントリの削除要否を判断
*/
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment