我们如何将数据值添加到hashmap <string,arraylist <string =“”>&gt; </string,>

时间:2014-11-18 20:00:25

标签: java hashmap

公共课EvilHangman {

public Map<String, ArrayList<String>> hashmap = new HashMap<String, ArrayList<String>>(); 
public Map<String, ArrayList<String>> hashmappattern = new HashMap<String, ArrayList<String>>(); 
public ArrayList<String> wordlist = new ArrayList<String>(); 
private String basekey="";
   /*
public EvilHangman(){
     hashmap = new HashMap<String, ArrayList<String>>();
     wordlist= new ArrayList<String>();
}
*/
public void readDictionary(String filename, int wordLength) throws IOException{     
    FileReader fr = new FileReader(filename);
    BufferedReader br = new BufferedReader(fr);
    PrintWriter writer = new PrintWriter("temp.txt", "utf-8");
    String line = br.readLine();
    while (line!=null){
        if (wordLength == line.length()){
            writer.println(line);
            wordlist.add(line);
        }
        line = br.readLine();
    }

    for (int i=0;i<wordLength;i++){
        basekey+="_";
    }
    System.out.println(basekey+"length"+basekey.length());
    hashmap.put(basekey, wordlist);     
    writer.close();
    br.close();
}   


public boolean checkLetter(String aletter){

    for (int i=0;i<wordlist.size();i++){
        char[] key = new char[wordlist.size()];

        for (int j=0;j<wordlist.get(i).length();j++){
            if (wordlist.get(i).charAt(j)==aletter.charAt(0)){
                key[j] = wordlist.get(i).charAt(j);
            }else{
                key[j] = '_';
            }
        }

        String wordkey = String.valueOf(key);
        System.out.println("Key = "+wordkey);

        if (hashmappattern.containsKey(wordkey)){   
            hashmappattern.get(wordkey).add(wordlist.get(i));
        }else{
            hashmappattern.put(wordkey, wordlist.get(i));
        }       
    }
}

}

我试图阅读arraylist wordlist,并且如果输入的字母(aletter)在单词中,我会扫描每一个单词。如果它在那里我把那封信放入char数组。经过所有单词后,我会有 a_,a_b 等模式。然后我将这些单词作为键并将值作为hashmap。如果找到相同的密钥,我想附加数据而不是替换。(我已经创建了arraylist但它不起作用因为我不能做put(字符串,字符串))。我应该如何解决这个问题。我试图使用hashmap

来制作evilhangman

1 个答案:

答案 0 :(得分:0)

您需要创建ArrayList并使用第一个元素填充它。然后将列表添加到hashmap:

    if (hashmappattern.containsKey(wordkey)){   
        hashmappattern.get(wordkey).add(wordlist.get(i));
    }else{
        ArrayList<String> list = new ArrayList<>();
        list.add(wordList.get(i));
        hashmappattern.put(wordkey, list);
    }