我正在尝试将对象添加到我的 ArrayList CoupleList 中,但我不断收到错误消息。
我的 WordCouple 类的构造函数
public class WordCouple {
private String first;
private String second;
public WordCouple (String first, String second) {
first = this.first;
second = this.second;
}
Run Code Online (Sandbox Code Playgroud)
我的 WordCoupleList 类的构造函数
import java.util.ArrayList;
public class WordCoupleList {
private ArrayList<WordCouple> coupleList;
public WordCoupleList(String[] words) {
for(int i = 0; i < words.length -1; i ++) {
for(int j = i+1; j < words.length; j++) {
coupleList.add(new WordCouple(words[i], words[i+j]));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是WordCouple从 a 中创建所有可能的实例String array,并将它们放在 an 中,ArrayList但我似乎无法初始化ArrayList.
示例:WordCoupleList构造函数传递了一个数组,如:{dog, cat, the ,cat}然后ArrayList看起来像[(dog,cat), (dog,the), (dog,cat), (cat,the), (cat,cat), (the,cat). 数组中的每个单词都必须与数组中后面存在的其他单词配对。
因为
private ArrayList<WordCouple> coupleList;
Run Code Online (Sandbox Code Playgroud)
声明一个类型的变量ArrayList但不初始化它(所以它是空的)。你需要类似的东西
private ArrayList<WordCouple> coupleList = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,更喜欢这样的List界面
private List<WordCouple> coupleList = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
或者只是在你的构造函数中初始化它。喜欢,
public WordCoupleList(String[] words) {
coupleList = new ArrayList<>();
for (int i = 0; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
coupleList.add(new WordCouple(words[i], words[i + j]));
}
}
}
Run Code Online (Sandbox Code Playgroud)