打卡
Topic sourceSystem.out.println(holder.getscore("bob") == 78 ?"测试成功" : "测试失败!");
代码如上,holder 在idea里面报红,请问一下您是如何解决的?
我的jdk是1.8,java se是15的版本,使用的idea是2020.1的版本
斗胆修正一下,这里应该并不需要在
Students(List<Student> list) { this.list = list; cache = new HashMap<>();}
中添加
for(Student s : list) {
cache.put(s.name, s.score);
}
首先题目的意思是用先用List查询,如果查询过一次且存在的学生信息,将其保存到cache当中,方便下次查询这个数据的时候直接用map缓存查询
如果在这里就将list当中的学生信息添加到cache,那这时的list和cache当中的信息其实就是一样的,那每次查询都先查询map,就不会经过list查询,这个list就是个摆设,没有任何作用,也就没有设置这个list的必要了。直接用map保存学生list信息即可了。
但这里还存在一个小细节,如果学生信息并不是两个字段 name和score,而是name , weight,score 三个字段时就用不了map来保存信息
因为map中保存信息是使用entry保存key&value ,也就是只能保存name&weight 或者name&score ,
这时用list保存学生信息,再用map当作缓存,可以创造出一个getWeight方法,可以创建cache: name&weight 和cache:name&score 分别来当作缓存来提高查询的效率
查询的效率是map>list的, 所以在信息量大的时候需要使用map作缓存提高查询效率
“但这里还存在一个小细节,如果学生信息并不是两个字段 name和score,而是name , weight,score 三个字段时就用不了map来保存信息
因为map中保存信息是使用entry保存key&value ,也就是只能保存name&weight 或者name&score ,
这时用list保存学生信息,再用map当作缓存,可以创造出一个getWeight方法,可以创建cache: name&weight 和cache:name&score 分别来当作缓存来提高查询的效率”——
key&value的关系并没有那么简单
例如map可以绑定name和整个student类,就如这一节老师写的例子
Map<String, Student> map = new HashMap<>();
map.put("Xiao Ming", s);
那么get()就可以返回跟name绑定的s,可以通过调用s.score、s.weight等来获取需要的字段信息
map可以绑定name和整个student类,那就是这样交作业了~
class Students { List<Student> list; Map<String, Student> cache; Students(List<Student> list) { this.list = list; cache = new HashMap<>(); } int getScore(String name) { // 优先在缓存的Map中查找,提高效率: Student student = this.cache.get(name); // 没找到,再到list中找 if (student == null) { Integer score = null; // TODO: score = findInList(name); if(score != null){ //存在,找到后放到缓存map中方便下次查找,提高效率 Student student1 = new Student(name, score); this.cache.put(name, student1); return score; }else { System.out.println("该学生:"+name+"在系统中不存在!"); return -1; } } return student.score; }
- 1
用户7570525982