我有一个cookie管理器类,它将cookie的列表按其域存储在Map中。在大多数情况下,大小将保持在100以下。
Map<String, CookieList> cookieMap;每次我为连接设置CookieList时,它都需要遍历所有域(String),检查它是否可接受,然后插入cookie。我将多次遍历地图。我有一个单独的列表持有域名和搜索,然后获得关键字的CookieList。
List<String> domainList;
// host is from the connection being set up
for (String domain : domainList) {
if (host.contains(domain)) {
CookieList list = cookieMap.get(domain);
// set up cookies
}
}由于我使用的是contains,所以不能直接从cookieMap获取密钥。这是一种好方法,还是我应该只迭代Map的EntrySet?如果是这样的话,LinkedHashMap在这个例子中会更好吗?
发布于 2013-03-10 02:10:23
您可以使用Map.keySet来获取域,而不是维护Map和List。
for (String domain : cookieMap.keySet()) {
if (host.contains(domain)) {
CookieList list = cookieMap.get(domain);
}
}这并不是低效的,因为for循环是O(n),而对cookieMap的调用是O(1)。
发布于 2013-03-10 02:21:17
Map<String, CookieList> coockieMap = new HashMap<String, CookieList>();
for (Map.Entry<Integer, CookieList> entry : coockieMap.entrySet()) {
if (host.contains(entry.getKey())) {
CookieList list = entry.getValue();
}
}希望这对你有帮助。
发布于 2013-03-10 03:12:51
我认为你的代码是非常优化的,如果你愿意,你可以使用
domainList.retainAll(hosts)在你的for循环之前,所以停止检查每一次循环。实际上,您的代码将如下所示:
List<String> hostList = new ArrayList<String>(domainList); // we don't want to edit domains
hostList.retainAll(host);
for (String hostEntry : hostList) { // I'd rename "host" so I can use it here
CookieList list = cookieMap.get(hostEntry);
// set up cookies
}https://stackoverflow.com/questions/15314085
复制相似问题