2016-12-16 81 views
0

我想將一個字符串(單個單詞)和一個int(他們的HashCodes)放入一個HasMap。在放置物品時我真的很掙扎。如何放置一個HashMap的HASHSET INSIDE?

// These approaches won't even run the code properly. 
map.put(word.hashCode(), word); 

// This type of approach makes my code work, but it's obviously not adding the words in. 
map.put(word.hashCode(), new HashSet<String>()); 

我一直在這裏嘗試了很多不同的時髦的東西,但我真的不能工作,如何正確添加單個單詞到地圖。有人可以幫助我理解如何首先將其放置到HashSet中,以便將其放入地圖中?

import java.io.*; 
import java.util.*; 
class Assign004{ 
public static void main(String args[]){ 

    // INT = HASHCODE 
    // STRING = WORD 
    Map<Integer, HashSet<String>> map = new HashMap<Integer, HashSet<String>>(); 

    // READ WORDS AND PLACE THEM INTO THE MAP 
    readFile(map); 
} 

public static void readFile(Map<Integer, HashSet<String>> map){ 
    String word = null; 

    try{ 
     File file = new File("src/Assign004_FILE.txt"); 
     Scanner r = new Scanner(file); 

     while(r.hasNext()){ 

      /* ******************************************************* 
         TEST CODE. TO CHECK IF IT'S READING IN THE WORDS 
      word = r.next(); 
      int hash = word.hashCode(); 
      System.out.print(word); 
      System.out.print(": " + hash + "\n"); 
      ******************************************************** */ 

      word = r.next(); 
      map.put(word.hashCode(), new HashSet<String>()); 
      System.out.print(map); 
     } 
     r.close(); 

    }catch(FileNotFoundException e){ 
     System.out.println("ERROR OPENING FILE"); 
    } 
    } 
} 
+2

爲什麼你顯式地調用'hashCode'?你真的需要直接使用hashcode嗎?這似乎不太可能。 – user2357112

+0

首先,使用'Set set = map.get(word.hashCode());'獲取集合,然後使用'set.add(word);'將該元素插入到集合中。 – marstran

+5

你能給我們一個關於你想在這裏實現什麼的高層次概述嗎? – berry120

回答

1

所以你有這個。

map.put(word.hashCode(), new HashSet<String>()); 

而你想把一個單詞放入該集合中,然後將該集合粘貼到地圖中?

然後你需要分解操作。

  1. 使一個Set對象
  2. wordSet
  3. 將集合(包含單詞)到地圖。

隨意評論/編輯您的問題,以澄清實際目標是什麼,但。

+1

前兩步也可以合併成['Collections.singleton(word)'](https://docs.oracle.com/ JavaSE的/ 8 /文檔/ API/JAVA/util的/ Collections.html#單-T-) – 4castle

0

您必須首先在外部聲明HashSet,然後才能將其放置在地圖中。

public class Helloworld { 

public static void main(String[] args) { 

    // Array with duplicates to check 

    String[] words = {"tomorrow", "today", "yesterday", "tomorrow", "today"}; 

    Map<Integer, HashSet<String>> map = new HashMap<Integer, HashSet<String>>(); 

    for(int i=0;i<words.length;i++) { 

    HashSet<String> word = new HashSet<String>(); 

    word.add(words[i]); 

    map.put(word.hashCode(), word); 

    } 
    System.out.println(map); 
} 

}

0

我們可以得到更大的畫面,但? haschCode可以產生碰撞。它被用來進行高效的搜索,這已經通過HashMap和HashSet的實現來完成。我認爲使用haschode作爲HashMap中的關鍵字不是一個好主意