就空间和运行时间而言,使用哈希表在目录中搜索特定文件是否高效?我想在需要时创建一次索引,能够在需要时重新索引但能够相对快速地进行搜索。
我将 hashCode 存储为键,将文件名存储为值。
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);
}
最佳答案
您的代码速度很快,但不正确:因为它存储散列,并且因为散列不是唯一的,所以您的搜索方法有返回误报的风险。
由于散列冲突,您无法通过检查从 map 返回的任何内容是否与搜索名称匹配来解决此问题。
更好的方法是存储字符串而不是哈希码。为此使用 HashSet of Strings,并通过调用 contains(name) 方法进行检查。
关于java - 使用哈希表在目录中查找文本文件是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42613108/