希望你做得很好
我在向ArrayList添加对象时遇到问题 我需要你的帮助来解决这个问题 每次当我要向selectedContacts ArrayList添加内容时,我得到了nullPointerException
ArrayList<ContactInfo> selectedContacts = new ArrayList<>();
public ArrayList<ContactInfo> getSelectedContacts()
{
int i = 0;
while (contacts.get(i).isCheck()==true)
{
ContactInfo info = contacts.get(i);
if(info != null)
selectedContacts.add(info);
i++;
}
return selectedContacts;
}
ContactInfo.Java
public class ContactInfo {
String name;
String number;
String email;
boolean check;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setCheck(boolean check) {
this.check = check;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public boolean isCheck() {
return check;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
答案 0 :(得分:-2)
由于您在selectedContacts
方法中返回getSelectedContacts
,因此最好在方法中移动ArrayList
声明。如;
public ArrayList<ContactInfo> getSelectedContacts()
{
ArrayList<ContactInfo> selectedContacts = new ArrayList<>();
int i = 0;
while (contacts.get(i).isCheck()==true)
{
ContactInfo info = contacts.get(i);
if(info != null)
selectedContacts.add(info);
i++;
}
return selectedContacts;
}