【问题标题】:Is it efficient to lookup text files in a directory using a hashTable?使用哈希表在目录中查找文本文件是否有效?
【发布时间】:2017-07-25 14:00:59
【问题描述】:

就空间和运行时间而言,使用哈希表在目录中搜索特定文件是否有效?我想创建一次索引,并在需要时重新创建索引,但搜索速度相对较快。

我将 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);
}

【问题讨论】:

  • hashCode 不是唯一标识符。只需使用 Set 来存储文件名。这就是您需要知道文件名是否存在的全部内容。
  • 我强烈建议您不要使用Hashtable。它已经过时了将近 19 年,并且在 Java 集合框架之前存在并且不是 Java 集合框架的一部分。使用替换Map 实现之一。

标签: java hashtable


【解决方案1】:

您的代码速度很快,但不正确:因为它存储哈希,并且哈希不是唯一的,您的搜索方法有返回误报的风险。

由于哈希冲突,您无法通过添加检查从地图返回的任何内容与搜索名称匹配来解决此问题。

更好的方法是存储字符串而不是哈希码。为此使用字符串的 HashSet,并通过调用 contains(name) 方法进行检查。

【讨论】:

    【解决方案2】:

    我没有理由不这样做,也不要想太多,只需编写当今有效的代码,如果结果证明效率低下,请寻找替代方案。

    【讨论】:

      猜你喜欢
      • 2016-10-29
      • 2011-08-16
      • 2020-02-14
      • 2017-07-08
      • 1970-01-01
      • 2012-05-12
      • 2010-11-20
      • 1970-01-01
      • 2013-04-08
      相关资源
      最近更新 更多