-1

可能重复:
在 java ArrayList 中搜索

如果我有一个ArrayList员工对象并且每个对象都包含一个 string:employeeName和 long: employeeNumber

如何根据员工编号在列表中搜索员工并返回员工对象?

4

3 回答 3

3

沿着这些思路。但最好将对象放在 id 为HashMap<Long,Employee>long 的位置,而 Employee 是属于该 id 的员工。

public Employee getEmployeeById(long empId){
    for(Employee e : employeeList) {
        if(e.getId() == empId){
            return e;
        }
    }
    return null;
}
于 2013-01-28T07:29:17.157 回答
1

我建议使用Map<int,string>where int 为您提供员工编号和字符串作为他们的姓名,这样迭代这种类型的集合将变得简单高效

于 2013-01-28T07:25:49.080 回答
0
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);
                            }
                        }
            }
}
于 2013-01-28T07:36:25.227 回答