[英]IndexOutOfBoundsException index 0 size 0 trying to edit an element in a populated arraylist
[英]Edit element in arraylist, find index?
我將創建兩種創建和更改客戶資料的方法。 創建配置文件沒有問題。 那里一切似乎進展順利。 但是,當我隨后進入並更改配置文件時,我發現它不起作用。
indexOf()給我-1,即使我搜索的值可用:S
有人對此有很好的解決方案嗎?
問題出在editProfile方法中!
public class Profile{
String name;
long id;
int accNr = 1000;
double balance;
}
ArrayList<Profile> profileList = new ArrayList<Profile>();
public boolean newProfile(long id, String name, int amount){
Profile newProfile = new Profile();
Profile accNr = new Profile();
int ACC = accNr.accNr++;
newProfile.accNr = ACC;
newProfile.id = id;
newProfile.name = name;
newProfile.balance = amount;
profileList.add(newProfile);
return true;
}
public void editProfile(long id, String newName){
int ID = (int)id;
System.out.print(ID);
int index = profileList.indexOf(id);
System.out.print(index);
profileList.get(index);
}
indexOf
方法將使用equals
方法確定列表中是否存在您的Profile
。 您必須重寫Profile
的equals
方法以返回正確的結果。
其次,它不會找到您的Profile
,因為您將long
傳遞給indexOf
,並且列表中不會找到long
或Long
。 如果必須long
檢索Profile
,則使用Map<Long, Profile>
而不是ArrayList<Profile>
更有意義。 然后,您可以調用get(id)
來檢索Profile
。 通常,如果覆蓋equals
,則應該覆蓋hashCode
方法 ,但是由於此處沒有將Profile
用作鍵,因此沒有必要。
profileList
包含Profile
實例,並且您試圖獲取long
的索引。
Profile
類中重寫equals
方法。 @Override
public boolean equals(Object obj) {
...
}
profileList
元素並手動檢查匹配項,例如: for (Profile element : profileList)
if (element.getID() == id)
...
可能您的Profile
需要覆蓋equals和hashCode方法。 然后可以生成Eclipse,就像舉個例子:
public class Profile {
String name;
long id;
int accNr = 1000;
double balance;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + accNr;
long temp;
temp = Double.doubleToLongBits(balance);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Profile other = (Profile) obj;
if (accNr != other.accNr)
return false;
if (Double.doubleToLongBits(balance) != Double
.doubleToLongBits(other.balance))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.