java使用哈希表查找目录中的文本文件是否有效?
在空间和运行时方面,使用哈希表搜索目录中的特定文件是否有效?我想创建一次索引,当你想,能够重新索引时,需要的,但能够搜索相对较快
我将哈希代码存储为键,文件名存储为值
private Map<Integer,String> indexDirectoryByHash()
{
Map<Integer,String> hashTable = new Hashtable<Integer, String>();
File directory = new File(this.path);
File[] directoryFiles = directory.listFiles();
String filename;
int hashCode;
for (int i = 0; i < directoryFiles.length; i++)
{
filename = directoryFiles[i].getName();
hashCode = filename.hashCode();
hashTable.put(hashCode,filename);
}
return hashTable;
}
public boolean searchFile(String filename)
{
if (hash.get(filename.hashCode()) != null)
return true;
else
return false;
}
好的,将其更改为使用集合而不是哈希表
private Set<String> indexDirectoryByHashSet()
{
Set<String> files = new HashSet<String>();
File directory = new File(this.path);
File[] directoryFiles = directory.listFiles();
String filename;
for (int i = 0; i < directoryFiles.length; i++)
{
filename = directoryFiles[i].getName();
files.add(filename);
}
return files;
}
public boolean searchFile(String filename)
{
return fileSet.contains(filename);
}
# 1 楼答案
我看不出有什么理由不这样做,不要真的想得太多,只需编写今天有效的代码,如果结果是无效的,那么就寻找替代方案
# 2 楼答案
您的代码很快,但不正确:因为它存储哈希,而且哈希不是唯一的,所以您的搜索方法有返回误报的风险
由于哈希冲突,您无法通过添加检查来修复此问题,以确保从映射返回的内容与搜索名称匹配
更好的方法是存储字符串而不是散列码。为此使用字符串的哈希集,并通过调用contains(name)方法进行检查