我将创建两种方法来创建和更改客户资料。创建配置文件没有问题。那里一切似乎都很顺利。但是,当我进去更改配置文件时,我发现它不起作用。
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
存在于列表中。您必须覆盖 equals
method在Profile
返回正确的结果。
其次,它不会找到你的 Profile
,因为您正在传递 long
至indexOf
,也不是 long
也不是Long
将在列表中找到。如果您必须检索Profile
通过long
,那么拥有 Map<Long, Profile>
更有意义而不是ArrayList<Profile>
。那么您可以调用get(id)
检索Profile
。通常,您应该覆盖 hashCode
method如果您覆盖 equals
,但是因为 Profile
这里没有被用作 key ,没有必要。
关于java - 编辑数组列表中的元素,找到索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21463340/