Java 当您不知道需要创建多少对象时,如何在ArrayList中存储对象?
背景:我将两段数据(都是Java 当您不知道需要创建多少对象时,如何在ArrayList中存储对象?,java,arraylist,Java,Arraylist,背景:我将两段数据(都是Strings)配对到ArrayList中。因此,我将成对的数据存储到一个对象中,然后将该对象存储到ArrayList中。我有一个文本文件,我为每个单词分配一个数字。然后,配对的数据就是字号(但我已经将它们都输入为字符串)。我不知道对于任何给定的文件大小,我需要多少对象 如何设置逻辑来迭代文本文件并填充我的ArrayList。这就是我到目前为止所做的: :PredictivePrototype.wordToSignature(aWord)//将单词转换为数字签名,例如“4
String
s)配对到ArrayList
中。因此,我将成对的数据存储到一个对象中,然后将该对象存储到ArrayList
中。我有一个文本文件,我为每个单词分配一个数字。然后,配对的数据就是字号(但我已经将它们都输入为字符串
)。我不知道对于任何给定的文件大小,我需要多少对象
如何设置逻辑来迭代文本文件并填充我的ArrayList
。这就是我到目前为止所做的:
:PredictivePrototype.wordToSignature(aWord)
//将单词转换为数字签名,例如“4663”
用于“home”之类的单词
你的代码似乎还可以。使用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() + ">");
}
}
}
import java.util.ArrayList;
公共类列表字典{
公共类WordSig{
私有字符串;
私有字符串签名;
公共字SIG(字符串字、字符串签名){
这个。单词=单词;
签名=签名;
}
公共字符串getWords(){
返回单词;
}
公共字符串getSignature(){
返回签名;
}
}
私有静态ArrayList字典=新ArrayList();
公共列表字典(){
//添加您想要的数量
对于(int i=0;i<10;i++)
添加(新单词sig(“key”+i,“value”+i));
}
公共静态类testListDictionary{
公共静态void main(字符串[]args){
新ListDictionary();
//测试输出
for(int i=0;i
这就是ArrayList
的美妙之处,你可以不断添加它,它会自动调整大小。我知道,但我不知道如何迭代生成更多对象……你认为你当前在循环时在做什么?特别是,您似乎已经在这样做了-那么,您的代码中有什么不起作用呢?这不是错误,这是对象的默认字符串表示。如果您希望它有所不同,则必须在WordSig
类中重写toString()
。再见,谢谢你的帮助。太好了。
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
}
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() + ">");
}
}
}