我正在做以下编程练习:URL Timestamps 。声明如下:
For my web app, I need a class that lets me store timestamps for URLs. For URLs that were never accessed, it should return -1. The class should be able to handle about a million calls in a few seconds.
我已经尝试过:
import java.net.URL;
import java.util.*;
public class UrlMap {
private static final Map<URL,Long> map = new HashMap<URL,Long>();
public void setTimestamp(URL url, long timestamp) {
map.put(url,timestamp);
}
public long getTimestamp(URL url) {
System.out.println("map: "+map);
return map.getOrDefault(url,-1L);
}
}
我很好奇,因为它没有通过执行测试,但它确实通过了示例测试。示例测试是:
import static org.junit.Assert.*;
import org.junit.Test;
import java.net.URL;
public class UrlMapTest {
@Test
public void testCodewars() throws Exception {
UrlMap map = new UrlMap();
URL url1 = new URL("http://www.codewars.com/");
long time1 = 12345L;
URL url2 = new URL("http://www.codewars.com/kata/url-timestamps/");
long time2 = 67890L;
map.setTimestamp(url1, time1);
map.setTimestamp(url2, time2);
assertEquals(time1, map.getTimestamp(url1));
assertEquals(time2, map.getTimestamp(url2));
}
@Test
public void testNew() throws Exception {
UrlMap map = new UrlMap();
URL url1 = new URL("http://www.codewars.com/");
URL url2 = new URL("http://www.codewars.com/kata/url-timestamps/");
assertEquals(-1, map.getTimestamp(url1));
assertEquals(-1, map.getTimestamp(url2));
}
}
我会尽可能地解释这个困难。执行测试,创建一个时间戳为12345L的“url1”。然后,在接下来的测试中,它创建一个没有时间戳的 url1。因此它期望得到 -1,因为它不应该存储时间戳,但它确实具有初始时间戳,因为 map 是静态的。
我认为这段代码通过了示例测试,因为在每个测试方法中都会创建一个新的 UrlMap。但是,在执行测试中,我认为正在重用完全相同的 urlMap 类。
为了尝试解决此问题,我已阅读: How can I initialise a static Map? How to update a value, given a key in a hashmap? What is an efficient way to implement a singleton pattern in Java?
我们如何使用单例模式存储 URL 和时间戳?
编辑:根据@JoakimDanielson 的回答,我们通过了之前讨论过的测试。然而超时,执行时间超过16000ms。我们如何改进这段代码以使其通过?
import java.net.URL;
import java.util.*;
public class UrlMap {
private Map<URL,Long> map;
public UrlMap(){
map=new HashMap<URL,Long>();
}
public void setTimestamp(URL url, long timestamp) {
map.put(url,timestamp);
}
public long getTimestamp(URL url) {
return map.getOrDefault(url,-1L);
}
}
最佳答案
只需实现一个普通类,其中 map 是实例变量,您的测试就会通过
public class UrlMap {
private Map<URL, Long> map;
public UrlMap() {
map = new HashMap<URL, Long>();
}
public void setTimestamp(URL url, long timestamp) {
map.put(url, timestamp);
}
public long getTimestamp(URL url) {
return map.getOrDefault(url, -1L);
}
}
关于java - 我们如何使用单例模式存储 url 和时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60462867/