将元素添加到hashmap的value数组时出错

时间:2016-09-25 00:29:59

标签: java arrays hashmap

我有一个我正在阅读的文本文件。我的目标是为文本文件中的每个单词创建一个hashmap,其中包含索引。索引定义为文本的一部分。在这种情况下,每100个字符被视为一个索引。出于某种原因,当我尝试向数组添加索引时,我收到错误。错误说“找不到符号”。我是java的新手,因为我刚开始编写它,所以任何帮助都将非常感激。我的代码如下:

import java.io.*;  //needed for File class below
import java.util.*;  //needed for Scanner class below

public class readIn {

    public static void readInWords(String fileName) {
        try {
            //open up the file
            Scanner input = new Scanner(new File(fileName));
            HashMap hm = new HashMap<String, ArrayList<String>>(); // Tells Java What datatypes are in the hashmap hm
            //Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
            int length = 0;
            int total = 0;
            int page = 0;
            while (input.hasNext()) {
                //read in 1 word at a time and increment our count
                String x = input.next();
                if (total < 100) {
                    length = x.length();
                    total = total += length;
                } else {
                    total = 0;
                    page++;
                }
                if (hm.get(x) == null) {
                    hm.put(x, new ArrayList<Integer>(page));
                } else {
                    hm.get(x).add(page);
                }

            }
            System.out.println(length);
            System.out.println(hm);
        } catch (Exception e) {
            System.out.println("Something went really wrong...");
        }
    }

    public static void main(String args[]) {
        int x = 10;  //can read in from user or simply set here

        String fileName = "test.txt";
        readInWords(fileName);
    }
}

2 个答案:

答案 0 :(得分:0)

//你需要输入cast hm.get(x)到像

这样的ArrayList中

((ArrayList的)hm.get(X))添加(页);

答案 1 :(得分:0)

您需要更改:

 HashMap hm = new HashMap<String, ArrayList<String>>();

   Map<String,ArrayList<Integer>> hm =  new HashMap<String, ArrayList<Integer>>(); 

如果您没有定义地图类型,get()会返回Object。通过定义Map<String,ArrayList<Integer>>,get将返回ArrayList<Integer>>


使用ArrayList<Integer>而不是ArrayList<String>,因为您将整数存储在arraylist中,而不是字符串。