【发布时间】:2014-12-09 02:33:55
【问题描述】:
编辑:我刚刚将 TreeMap 更改为 HashMap,现在它工作了一点,但仍然没有做我需要它做的事情..
嘿,这件事我已经坚持了很长时间了。
我的目标是从文件sequence.txt 中获取文本,然后调用传递扫描仪s 和整数n 的构造函数。在构造函数内部,我的目标是从sequence 中读取n 单词并将其保存在ArrayList 中,然后内部映射应该能够在n 单词序列之后立即获取单词并保持计数n + thisWord 存在多少次。
所以,一个例子是这些 n(或 5)个单词:
so an to me for
然后第六个可能是and,所以在原始地图中它会是:
map.put(arrList, innerMap);
其中 arrList 将包含 so, an, to, me, for,而 innerMap 看起来像这样 and | 1
然后从那里开始添加每个新的,对于相同的序列,它会将整数加一。我会担心第二部分,但我什至无法让我的代码工作,而且我不知道我做错了什么。这是我的构造函数:
public RandomWriter(Scanner s, int n) {
Map<String, Integer> valMap = new HashMap<String, Integer>();
this.s = s;
this.n = n;
map = new HashMap<>(); `
Queue<String> tmp = new LinkedList<String>();
for (int i = 0; i < n; i++) {
tmp.add(s.next());
}
while (s.hasNext()) {
ArrayList<String> tmpList = new ArrayList<String>();
tmpList.addAll(tmp);
String current = s.next();
if (!valMap.containsKey(current)) {
valMap.put(current, 1);
} else {
valMap.put(current, valMap.get(current + 1));
}
tmp.add(current);
tmp.remove();
map.put(tmpList, valMap);
}
// s.next();
System.out.println(map.keySet());
}
在更改为 HashMap 后,它现在打印出来如下:
[[today, day], [me, and], [so, if], [in, for], [for, you], [top, in], [sent, receive], [for, many], [on, top], [or, on], [do, do], [side, so], [so, when], [under, on], [many, much], [to, do], [row, on], [for, when], [when, become], [dog, house], [toy, your], [many, is], [won, do], [become, inside], [why, to], [to, spell], [me, you], [school, under], [too, your], [hit, high], [can, do], [is, to], [for, how], [receive, get], [on, me], [animal, your], [to, animal], [inside, to], [your, for], [cat, many], [who, me], [spell, word], [do, cat], [house, live], [how, can], [your, who], [word, sent], [to, today], [canvas, word], [on, for], [low, ball], [which, many], [animal, if], [much, mouse], [live, living], [your, sent], [if, how], [high, kill], [ball, hit], [if, so], [in, side], [get, which], [you, if], [so, for], [do, if], [get, toy], [so, row], [if, to], [to, if], [win, won], [how, when], [inside, in], [dog, squirrel], [you, to], [and, you], [so, or], [word, school], [mouse, for], [for, why], [day, dog], [squirrel, fish], [your, if], [cat, dog], [for, which], [to, when], [more, for], [to, your], [which, cat], [living, canvas], [kill, win], [you, low], [when, inside], [fish, animal], [do, so], [many, more], [to, too], [when, to]]
这是它正在进入的地图:
private Map<ArrayList<String>, Map<String, Integer>> map;
【问题讨论】:
-
不清楚您是如何从您的描述中获取“内部地图”的值的。至于错误,这是因为
ArrayList不可比较(因此不能存储在TreeSet中)