Java 在ArrayList中搜索员工编号
可能重复:Java 在ArrayList中搜索员工编号,java,search,arraylist,Java,Search,Arraylist,可能重复: 如果我有一个employee对象的ArrayList,并且每个对象都包含一个字符串:employeeName和long:employeeNumber 如何搜索给定员工编号的员工列表并返回员工对象?我建议使用Map,其中int将为您提供员工编号和姓名字符串,这样就可以轻松高效地遍历此类集合。但是最好将对象放在HashMap中,其中long是id,Employee是属于该id的雇员 public Employee getEmployeeById(long empId){ for
如果我有一个employee对象的
ArrayList
,并且每个对象都包含一个字符串:employeeName
和long:employeeNumber
如何搜索给定员工编号的员工列表并返回员工对象?我建议使用
Map
,其中int将为您提供员工编号和姓名字符串,这样就可以轻松高效地遍历此类集合。但是最好将对象放在HashMap
中,其中long是id,Employee是属于该id的雇员
public Employee getEmployeeById(long empId){
for(Employee e : employeeList) {
if(e.getId() == empId){
return e;
}
}
return null;
}
公共级电磁脉冲{
int-id;
字符串名;
公共emp(整数i,字符串名称)
{
超级();
这个id=i;
this.name=名称;
}
}
///////////
公开课考试{
公共静态void main(字符串[]args)
{
int=3;
ArrayList empList=新的ArrayList();
新增(新emp(1,“侯赛因1”);
新增(新emp(2,“侯赛因2”);
新增(新emp(3,“侯赛因3”);
for(emp currenp:empList)
{
if(currenp.id==givenEmpId)
{
System.out.println(“emp name is===>>”+currenp.name);
}
}
}
}
您尝试过什么?您可以编写自己的过滤器,也可以进行迭代搜索并匹配自己。您可以比较它们,然后返回对象:)哇@KevinEsche,这很有意义。:)@BlackHatShadow是的,它是这个问题最简单的答案,没有任何代码是的,如果OP需要做大量的查找HashMap
更好。你缺少一个返回语句。returnnull
在for循环之后将修复它。@Marcelo你是对的,我没有思考就写了这个。修正了我的答案,谢谢。
public class emp {
int id ;
String name;
public emp(int i, String name)
{
super();
this.id = i;
this.name = name;
}
}
///////////
public class Test {
public static void main(String[] args)
{
int givenEmpId = 3;
ArrayList<emp> empList = new ArrayList<emp>();
empList.add(new emp(1,"hussain1"));
empList.add(new emp(2,"hussain2"));
empList.add(new emp(3,"hussain3"));
for ( emp currEmp : empList)
{
if(currEmp.id==givenEmpId)
{
System.out.println("emp name is===>>"+currEmp.name);
}
}
}
}