繁体   English   中英

在链表java中查找元素

[英]find element in linked list java

我有一个完整的员工链接列表用于测试,我想迭代它,看看是否找到一个员工然后返回true,这确实有点工作,但它只会找到列表中的最后一个员工,我做错了什么? 此外,我有不同类型的员工,例如从帐户类继承的经理,对不起,如果那令人困惑! 对不起还是个初学者!! 谢谢

这是我添加帐户的列表:

LinkedList<Account> Accounts = new LinkedList<Account>(); 

Employee John = new Account("John", "password1");
Manager Bob = new Account("Bob", "password2");   

以下是查找员工/帐户的方法。

private boolean check(String employee) {

                for (Account e : Accounts) {
               if (e.getEmployee().equals(employee)) {
                   return true;
               }
               }       
                return false;


    }

编辑:下面是我添加的代码,但它只适用于最后一个用户。 如果在链表中找到帐户名,我希望该方法返回true,以便系统可以继续并询问更多信息等..,name变量位于我的Account类中

private boolean check(String employee){
     for(Account a : accounts){
        if(a.name.equals(employee)){
            return true;
        }
     }
     return false;
 }

无需迭代, list的contains方法将为您完成

if (e.getEmployee().equals(employee))

这将比较对象是否相同,这意味着它们在内存中是相同的

您需要指定对象的哪些属性必须相等,以便在查看一个或多个属性时逻辑地说2个不同的对象是相同的。

例如

John.equals(Bob) 

将永远不会是真的,但如果对象John和对象Bob都具有name属性,则为String =“Alex”

John.getName().equalsIgnoreCase(Bob.getName())

将是真的

没有必要迭代列表。 因此,您可以使用替换您的检查方法

  private boolean check(String employee) {
           return Accounts.contains(employee);
}

你应该进一步替换

 Employee John = new Accounts("John", "password1");
 Manager Bob = new Accounts("Bob", "password2");

 Employee John = new Account("John", "password1");
 Manager Bob = new Account("Bob", "password2");

你有两个选择。 第一种是更改check方法的签名以使用Account对象,或者从Account对象中提取字段以进行比较:

private boolean check(Account account){
      return accounts.contains(account);
}

但是,这需要您为Account实现自定义equals()方法:

@Override
public boolean equals(Object obj){
    if(obj instanceof Account){
         Account acct = (Account)obj;
         //Compare any internal fields that mean it's "equal"
         if(acct.prop1 == this.prop1 && ...) {
            return true;
          }
    }

    return false;
}

您的另一个选择是与迭代中的特定字段进行比较:

private boolean check(String emp){
     for(Account a : accounts){
        if(a.stringProperty.equals(emp)){
            return true;
        }
     }
     return false;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM