【发布时间】:2014-04-21 20:25:28
【问题描述】:
如果这是一个愚蠢的问题,我很抱歉,但我是 Java 链表和数组表的新手。
我想做的是: 我有一个逐字逐句运行的文本文件。我想创建一个链表的 Arraylist,文本中的每个 uniqye 单词在链表中后跟它在文本中的单词。
考虑这段文字:猫走到红树前。
我希望 LinkedLists 的 Arraylist 是这样的:
那-猫-红色
|
猫 - 走路
|
到 -
|
红色 - 树
我现在拥有的是这样的:
while(dataFile.hasNext()){
secondWord = dataFile.next();
nWords++;
if(nWords % 1000 ==0) System.out.println(nWords+" words");
//and put words into list if not already there
//check if this word is already in the list
if(follows.contains(firstWord)){
//add the next word to it's linked list
((LinkedList)(firstWord)).add(secondWord);
}
else{
//create new linked list for this word and then add next word
follows.add(new LinkedList<E>().add(firstWord));
((LinkedList)(firstWord)).add(secondWord);
}
//go on to next word
firstWord = secondWord;
}
它给了我很多错误。 我怎样才能做到最好? (使用链表,我知道哈希表和二叉树更好,但我需要使用链表)
【问题讨论】:
-
忘记使用
LinkedList或ArrayList,因此也忘记了这种类型转换。将您的变量声明为List接口,并在初始化时确定正确的类实现。 -
那我该怎么做呢?我很困惑。
标签: java arraylist linked-list add