搜狗第一题-自定义Map
这道题是三道题里面最简单的一道,直接继承LinkedHashMap,然后重写removeEldestEntry方法
import java.util.*;
public class Main<K, V> extends LinkedHashMap<K, V> {
private int maxSize;
public Main(int maxSize) {
super(maxSize + 1, 0.999999f, true);
this.maxSize = maxSize + 1;
}
@ Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
if (size() > maxSize - 1) {
System.out.println(eldest.getKey() + " " + eldest.getValue());
return true;
}
return false;
}
private static Main<String, Long> map;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
map = new Main<>(size);
in.nextLine();
while (in.hasNext()) {
String[] inputs = in.nextLine().split(" ");
putEntry(inputs[0], Long.parseLong(inputs[1]));
}
}
private static void putEntry(String key, Long value) {
if (map.containsKey(key)) {
if (value > map.get(key)) {
map.put(key, value);
}
} else {
map.put(key, value);
}
}
}
腾讯云智研发成长空间 273人发布