簡體   English   中英

正確使用“哈希表”的方式?

[英]Correct Way to Use “Hashtable”?

我是Hashtables的新手,正在嘗試了解它們如何完全發揮作用。 我需要確定一個字符串是否出現在包含大約100,000個字符串的大文件中,每個字符串都在各自的行上。 有人告訴我,哈希表比LinkedList或ArrayList在運行時都為O(n)的效率要高得多。

我已經研究了Java中的HashTable類,但是由於“ put”方法需要一個鍵以及對象,所以我不明白我將如何精確地輸入文件中的每個字符串。

我想我可以使用掃描程序遍歷文件中的每個字符串,但是如何將它們輸入到Hashtable中,以及如何在HashTable中使用contains()方法?

對我來說,這聽起來像是HashSet 檢查出!

您只放入值,這些值以不同的方式存儲(沒有重復的值)。 然后,您可以僅調用contains方法,以檢查您的String是否位於Set中。

您可以將字符串放入HashSet

Set yourStrings = new HashSet<String>();

for (String line : yourFile) {
    yourStrings.add(line);
}

然后檢查是否存在特定的字符串:

if (yourStrings.contains("Hi!")) {
    // It's present
}
else {
    // It's not present
}

Hashtable相當老,已經被HashMap取代。 還有HashSet 兩者都使用哈希表,但是它們具有不同的用途。 當您要將某種值與每個鍵相關聯時,可以使用HashMap 例如,您可以使用它來查找某人的姓名並獲取他們的電話號碼。 但是, HashSet只存儲沒有任何值的鍵。 您可以使用它只是將名稱添加到集合中,然后稍后檢查名稱是否在集合中。

正如Luiggi在評論中提到的那樣, HashMapHashSet只是MapSet特定實現; 這些實現使用哈希表,但是可以使用這些類的其他實現。 構造表時,需要使用HashMapHashSet ,但是通常應將變量簡單地聲明為MapSet ,因為那樣可以將HashMapHashSet替換為其他實現相同方法的類。 這樣,您就不必局限於特定的實現。

您需要一個HashSet來存儲文件的每一行。

*僅當您對文件中每個String的出現次數感興趣時,才可能需要HashMap。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;


public class MyFileUtils {

//this can be omitted, just added to increase speed 
//when requiring multiple searches in the same file, to avoid recalculations.
//Use it only if you need to search in one file ONLY
private static Set<String> stringLines = null;

/*
 * Get a HashSet of all the (distinct) lines in a file
 */
public static Set<String> getStringLinesFromFile (String filePath) {
    //this can be omitted, just added to support fast multiple calls of this function 
    if (stringLines != null) return stringLines;

    Set<String> stringLines = new HashSet<String>(); 

    Scanner scanner = null;
    try {
        scanner = new Scanner(new File(filePath));
        while (scanner.hasNextLine())
            stringLines.add(scanner.nextLine());
    } catch (FileNotFoundException e) {
        System.out.println("File does not exist");
    } finally {
        if(scanner != null)
            scanner.close();
    }
    //as the first line, this can be omitted, just added to support fast multiple calls of this function 
    MyFileUtils.stringLines = stringLines;

    return stringLines;
}

/*
 * Call this method to search for a stringLine in a file
 */
public static boolean checkIfStringExistsInFile(String filePath, String aStringLine) {
    return getStringLinesFromFile(filePath).contains(aStringLine);
}

//Test
public static void main (String args[]) {
    System.out.println(checkIfStringExistsInFile("test.txt", "Hello World"));
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM