自定义对象的Arraylist是否包含其他自定义对象的arraylists?那怎么会有用呢?
我试过了:
public class BankAccount {
private String mTitle;
private float mBalance;
private ArrayList<sE> mHistory;
public BankAccount(String title) {
mTitle = title;
mPrefFile = null;
mBalance = 0;
mHistory = new ArrayList<>();
}
public void changeBalance(float newBalance) {
mBalance = newBalance;
}
public String getTitle() {
return mTitle;
}
public String getPrefFile() {
return mPrefFile;
}
public float getBalance() {
return mBalance;
}
public ArrayList<sE> getHistoryArrayList() {
return mHistory;
}
public void addToHistoryArrayList(String Title, Boolean IsEarning, float Amount) {
mHistory.add(new sE(Title, IsEarning, Amount));
}
//sE stands for Spending/Earning
public class sE {
private String mTitle;
private Boolean mIsEarning;
private float mAmount;
public sE(String Title, Boolean IsEarning, float Amount) {
mTitle = Title;
mIsEarning = IsEarning;
mAmount = Amount;
}
public String getTitle() {
return mTitle;
}
public Boolean getIsEarning() {
return mIsEarning;
}
public float getAmount() {
return mAmount;
}
}
}
但是当尝试将sE对象添加到History Array时,它会给我一个错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean java.util.ArrayList.add(java.lang.Object)'
我该如何解决?谢谢你的帮助!
答案 0 :(得分:0)
上面发布的代码是正确的。您正在构造函数中即时创建新的ArrayList,然后在其中添加新的sE。没关系。但是当你尝试创建嵌套的ArrayList时,你必须为你添加的每个元素创建新的ArrayList元素。
ArrayList<ArrayList<sE>> nestedList = new ArrayList<>();
同时添加
nestedList.add(new ArrayList<>());
使用
为其添加元素nestedList.get(0).add(new sE(...));
就是这样。