Discuss / Java / 练习:请编写一个根据name查找score的程序,并利用Map充当缓存,以提高查找效率

练习:请编写一个根据name查找score的程序,并利用Map充当缓存,以提高查找效率

Topic source

韦雪松

#1 Created at ... [Delete] [Delete and Lock User]
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Student {
    String name;
    int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

class Students {
    List<Student> list;
    Map<String, Integer> cache;

    Students(List<Student> list) {
        this.list = list;
        cache = new HashMap<>();
    }

    /**
     * 根据name查找score,找到返回score,未找到返回-1
     *
     * @param name 姓名
     * @return score 分数
     */
    int getScore(String name) {
        Integer score = cache.get(name);
        if (score == null) {
            score = findInList(name);
            if (score != null) cache.put(name, score);
        }
        return score == null ? -1 : score;
    }

    Integer findInList(String name) {
        for (Student item : list) {
            if (name.equals(item.name)) {
                return item.score;
            }
        }
        return null;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student("Bob", 78));
        list.add(new Student("Alice", 85));
        list.add(new Student("Brush", 66));
        list.add(new Student("Newton", 99));
        Students holder = new Students(list);
        System.out.println(holder.getScore("Bob") == 78 ? "测试成功!" : "测试失败!");
        System.out.println(holder.getScore("Alice") == 85 ? "测试成功!" : "测试失败!");
        System.out.println(holder.getScore("Tom") == -1 ? "测试成功!" : "测试失败!");
    }
}

  • 1

Reply