Discuss / Java / 作业

作业

Topic source

shadowTy

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {
	public static void main(String[] args) {
		List<Student> list = List.of(new Student("Bob", 78), new Student("Alice", 85), new Student("Brush", 66),
				new Student("Newton", 99));
		var 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 ? "测试成功!" : "测试失败!");
	}
}

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

	Students(List<Student> list) {
		this.list = list;
		cache = new HashMap<>();
//		for(Student s : list) {
//			cache.put(s.name, s.score);
//		}
	}

	int getScore(String name) {
		// 先在Map中查找:
		Integer score = this.cache.get(name);
		if (score == null) {
			// TODO:
			score = findInList(name);
		} else {
			cache.put(name, score);
		}
		return score == null ? -1 : score.intValue();
	}

	Integer findInList(String name) {
		for (var ss : this.list) {
			if (ss.name.equals(name)) {
				return ss.score;
			}
		}
		return null;
	}
}

class Student {
	String name;
	int score;

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

感谢分享!

  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();
    }

个人理解,欢迎交流!

東寶一童

#3 Created at ... [Delete] [Delete and Lock User]

老师说的缓存的意思就是用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

Reply