作业
Topic source感谢分享!
int getScore(String name) {
// 先在Map中查找:
Integer score = this.cache.get(name);
/////////////////////////////////////////
if (score == null) {
score = findInList(name);
} else {
cache.put(name, score);
}
/////////////////////////////////////////
return score == null ? -1 : score.intValue();
}
我的理解:在 Map 找,如果找不到 score 就在 list 中找;如果找到就加入 Map。
目的:为了下次查找更快!
是这样理解的吧?
但是,
这不就成了,在 Map 中找到又放到 Map 中等于没放;在 Map 中找不到就到 List 中找。如果,Map 一开始为空的话,等于你每次都到 List 中找,那 Map 缓存都没用到了。
我的做法:在 Map 找,如果找不到就到 List 中找(如果在 List 中找到,就加入 Map 以便下次查找)。
int getScore(String name) {
// 先在Map中查找:
Integer score = this.cache.get(name);
// 若找不到,就到 List 中找.
if (score == null) {
score = findInList(name);
// 若找到, 就放到用于缓存的 Map 中, (目的是: 下次就快了!)
if (score != null)
cache.put(name, score);
}
return score == null ? -1 : score.intValue();
}
个人理解,欢迎交流!
老师说的缓存的意思就是用map嘛,提示也很清楚了,无论如何先在cache中匹配键,找到了当然皆大欢喜,因为map匹配快嘛,然后score就拿到了啊,就返回啊。如果score没找到,那就用findInList方法,然后将这个没有找到的键值对放入(注意cache创建时里面没有任何东西)cache,这样下次一来就直接去cache里快速获取答案啦。不太明白答主在else里的操作。
int getScore(String name) { // 先在Map中查找: Integer score = this.cache.get(name); if (score == null) { // TODO: cache.put(name, score); score = findInList(name); } return score == null ? -1 : score.intValue();}
- 1
shadowTy