我有一个ArrayList
,其中通过以下代码生成并存储对象:
btSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
members.add(new member (name, id, mail, ccard, address));
Toast.makeText(MemReg_activity.this, "Member Added", Toast.LENGTH_LONG).show();
etname.setText("");
}
});
现在我想通过其他 Activity 中的名称
搜索此列表
有没有办法做到这一点 ?
如果没有,除了使用 ArrayList 之外还有其他方法可以帮助我做到这一点吗?
成员(member)等级
package com.fawzyx.movie_rental_store;
public class Member extends Customer {
String id;
String mail;
String ccard;
String address;
public Member (String name, String id, String mail, String ccard, String address) {
this.name = name;
this.id = id;
this.mail = mail;
this.ccard = ccard;
this.address = address;
}
public String getName()
{
return name;
}
}
最佳答案
如果name
是唯一的,则通过name
查找成员
的方法:
public Member findMemberByName(String name) {
// go through list of members and compare name with given name
for(Member member : members) {
if (member.getname().equals(name)) {
return member; // return member when name found
}
}
return null; // return null when no member with given name could be found
}
如果 name
不唯一,该方法将返回一个包含所有匹配项的 ArrayList
public ArrayList<Member> findMemberByName(String name) {
ArrayList<Member> matches = new ArrayList<Member>();
// go through list of members and compare name with given name
for(Member member : members) {
if (member.getname().equals(name)) {
matches.add(member); // adds matching member to the return list
}
}
return matches; // return the matches, which is empty when no member with the given name was found
}
要在另一个Activity
中执行此操作,您必须将members
传递给另一个Activity。请参阅Starting another Activity
关于android - 通过对象的属性之一搜索对象的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817209/