[英]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.