-1

我正在尝试在 ArrayList 中使用 contains 方法,我在其中存储了 Employee 类型的对象。但是当我使用这个方法时,即使我在 Employee 类中实现了 equals 方法,它总是返回 false

这是我尝试过的:

员工等级

public class Employee {
   .
   .
   .
@Override
public boolean equals(Object o){

  if(o instanceof Employee)
  {
    Employee e = (Employee) o;
    return this.id==(e.id);
  }
    return false;
 }

   @Override
    public int hashCode() {
      int hash = 7;
      hash = 79 * hash + (int) (this.id ^ (this.id >>> 32));

      return hash;
  }

测试类

public class Test {


LinkedList <Employee>list=new LinkedList <Employee>();
Employee e=new Employee();
long id=0;

     e.setId(20710456);
     list.add(e);

      e.setId(30560432);
     list.add(e);


public void Edit()
{       
         id=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the id of the 
          employee"));

          e.setId(id);

            System.out.print(list.contains(e.getId()));

    if(list.contains(e.getId())){
                 .
                 .
                 //rest of the code

            }
    }
 }
4

3 回答 3

7

您正在呼叫list.contains(e.getId()),但该列表不包含 ID 号 - 它包含Employees。我怀疑你的意思list.contains(e)

于 2013-04-03T21:03:09.340 回答
0

你应该调用 list.contains(e)。该列表包含员工而不是员工 ID。

于 2013-04-03T21:04:01.527 回答
0

只需在您的列表上循环进行比较

例如:

for (Employee em: list){
  if(em.getId()=e.getId()){
//your logic
  }
}
于 2013-04-03T21:07:22.290 回答