如何在HashMap中放置HashSets?

时间:2016-12-16 23:05:17

标签: java

我试图将一个String(单个单词)和一个int(他们的HashCodes)放入HasMap。在将物品放入室内时,我真的很挣扎。

// 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");
    }
  }
 }

3 个答案:

答案 0 :(得分:1)

所以你有这个。

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

你想在集合中加入一个单词,然后将该集合粘贴到地图中?

然后你需要分解操作。

  1. 制作Set对象
  2. word放入Set
  3. 将集合(包含单词)放入地图中。
  4. 随意评论/编辑您的问题,以澄清实际目标是什么。

答案 1 :(得分: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);
}

}

答案 2 :(得分:0)

我们可以了解大局吗? haschCode可以生成冲突。它用于进行有效的搜索,这已经通过HashMap和HashSet的实现完成。我不认为在哈希地图中使用haschode作为关键是个好主意

相关问题