背景:我正在将两个数据(String
s)配对到ArrayList
。因此,我将配对数据存储到对象中,然后将此对象存储到ArrayList
中。我有一个文本文件,每个单词,我分配一个数字。然后配对的数据是字数(但我将它们都输入为String
)。我不知道任何给定文件大小需要多少个对象。
如何设置逻辑以迭代文本文件并填充ArrayList
。这是我到目前为止所做的:
:PredictivePrototype.wordToSignature(aWord)
//将单词转换为数字签名,例如“"4663"
"home"
public class ListDictionary {
private static ArrayList<WordSig> dictionary;
public ListDictionary() throws FileNotFoundException {
File theFile = new File("words");
Scanner src = new Scanner(theFile);
while (src.hasNext()) {
String aWord = src.next();
String sigOfWord = PredictivePrototype.wordToSignature(aWord);
// assign each word and its corresponding signature into attribute
// of an object(p) of class WordSig.
//WordSig p1 = new WordSig(aWord, sigOfWord);
//Then add this instance (object) of class Wordsig into ArrayList<WordSig>
dictionary.add(new WordSig(aWord, sigOfWord));
}
src.close();
}
存储配对数据的其他类:
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
}
答案 0 :(得分:0)
您的代码似乎没问题。使用ArrayList,您可以根据需要添加任意数量的元素(通过使用add()函数)。
以下是一个例子:
import java.util.ArrayList;
public class ListDictionary {
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
public String getWords() {
return words;
}
public String getSignature() {
return signature;
}
}
private static ArrayList<WordSig> dictionary = new ArrayList<WordSig>();
public ListDictionary() {
// add as many as you want
for ( int i=0; i < 10; i++)
dictionary.add(new WordSig("key"+i, "value"+i));
}
public static class testListDictionary {
public static void main(String[] args) {
new ListDictionary();
// test output
for ( int i=0; i < dictionary.size(); i++ )
System.out.println( "<" + dictionary.get(i).getWords() + "|"
+ dictionary.get(i).getSignature() + ">");
}
}
}