[英]How can I create cache map in this situation?
例如,我在代码中占据了一定的位置,可以从磁盘接收许多文件(其中许多文件是相同的),然后进一步解组。
final File configurationFile = getConfigurationFile();
FileOutputStream fileOutputStream = new FileOutputStream(configurationFile);
Marshaller.marshal(configObject, fileOutputStream);
显然,我可以为它们创建一个特殊的缓存映射以提高性能(以免一次又一次地解组相同的文件)。 就我而言, HashMap
实现就足够了。
问题是: 我应该为此使用什么钥匙?
configurationFile.hashCode()
对此非常不好?
感谢您的所有回答!
您也可以使用哈希集,而不必担心密钥。
if(hashset.add(file)) {
// do unmarshling;
} else {
//do nothing
}
如果可以添加对象,则Hashset.add()方法返回true。 如果您尝试添加重复的条目,则它将返回false,因为在集合中不允许重复。
...相同的文件一次又一次...
什么是相同的?
如果文件内容决定,则可以使用文件内容的哈希(例如MD5,SHA1,SHA256)作为键。
如果文件名必须相同,只需使用文件名作为键即可。
如果是文件路径,则使用文件的完整路径作为键( File.getCanonicalPath()
)。
使用规范路径而不是绝对路径( 有关差异的说明 ),并将其放入HashSet中。 设置不允许重复的值。 如果您尝试添加一个已经存在的值,它将返回false,否则返回true。
示例代码(未经测试):
Set<String> filesMarshalled= new HashSet<>();
...
final File configurationFile = getConfigurationFile();
if (filesMarshalled.add(configurationFile.getCanonicalPath())) {
//not marshalled yet
FileOutputStream fileOutputStream = new FileOutputStream(configurationFile);
Marshaller.marshal(configObject, fileOutputStream);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.