【问题标题】:search in java ArrayList在 java ArrayList 中搜索
【发布时间】:2010-11-02 09:11:16
【问题描述】:

我正在尝试找出在ArrayList 中通过 ID 号搜索客户的最佳方式。下面的代码不起作用;编译器告诉我我缺少return 语句。

Customer findCustomerByid(int id){
    boolean exist=false;

    if(this.customers.isEmpty()) {
        return null;
    }

    for(int i=0;i<this.customers.size();i++) {
        if(this.customers.get(i).getId() == id) {
            exist=true;
            break;
        }

        if(exist) {
            return this.customers.get(id);
        } else {
            return this.customers.get(id);
        }
    }

}

//the customer class is something like that
public class Customer {
    //attributes
    int id;
    int tel;
    String fname;
    String lname;
    String resgistrationDate;
}

【问题讨论】:

  • 一个主要的 Java 良好实践是总是使用大括号,即使该块只有一个句子,以避免像你这样的问题

标签: java search arraylist


【解决方案1】:

其他人指出了您现有代码中的错误,但我想进一步采取两个步骤。首先,假设您使用的是 Java 1.5+,您可以使用 增强的 for 循环获得更高的可读性:

Customer findCustomerByid(int id){    
    for (Customer customer : customers) {
        if (customer.getId() == id) {
            return customer;
        }
    }
    return null; 
}

这也消除了在循环之前返回null 的微优化——我怀疑你会从中得到任何好处,而且它是更多的代码。同样,我删除了exists 标志:一旦知道答案就返回会使代码更简单。

请注意,在您的原始代码中,我认为您有一个错误。发现索引 i 处的客户具有正确的 ID,然后您返回索引处的客户 id - 我怀疑这是否真的是您想要的。

其次,如果您要通过 ID 进行大量查找,您是否考虑过将您的客户放入Map&lt;Integer, Customer&gt;

【讨论】:

    【解决方案2】:

    编译器正在抱怨,因为您当前的 for 循环中有“if(exist)”块。它需要在它之外。

    for(int i=0;i<this.customers.size();i++){
            if(this.customers.get(i).getId() == id){
                exist=true;
                break;
            }
    }
    
    if(exist) {
        return this.customers.get(id);
    } else {
        return this.customers.get(id);
    }
    

    话虽如此,有更好的方法来执行此搜索。就个人而言,如果我使用的是 ArrayList,我的解决方案将类似于 Jon Skeet 发布的解决方案。

    【讨论】:

    • 我强烈怀疑代码仍然被破坏(注意最后对customers.get的论点)。事实上,它还有一个“if/else”,两个分支都有相同的代码,这一事实也很可疑!
    • 我同意,乔恩。此外,当然还有更好的方法来执行搜索(正如其他几位发帖人所指出的那样)。
    • 为什么最后会有 if else ?您可以删除支票并返回 this.customers.get(id);它与将 if else 阻塞在那里并删除该代码中不需要的额外检查相同。我这样做的方式是如果它确实存在则返回true,如果它不存在则返回false,您甚至可以删除语句的else部分,因为一旦if语句为true,那么它无论如何都不会继续执行
    【解决方案3】:

    就我个人而言,我现在很少自己编写循环,因为我可以摆脱它......我使用 Jakarta commons 库:

    Customer findCustomerByid(final int id){
        return (Customer) CollectionUtils.find(customers, new Predicate() {
            public boolean evaluate(Object arg0) {
                return ((Customer) arg0).getId()==id;
            }
        });
    }
    

    耶!我保存了一行!

    【讨论】:

    • 您每次编写 find() 函数时都节省了一行 :-) 这可不容小觑!
    • 您可能会在每次编写该代码时“保存”一行代码,但我敢打赌,如果您查看了 find 函数的工作原理,您会发现它使用了 for 循环。因此,必须问他们自己,您是否真的“保存”了任何行或在下划线代码中添加了更多行? ;)
    • @Spider 运行时执行只是衡量代码的一种方式...减少重复代码还有其他好处。
    【解决方案4】:
    Customer findCustomerByid(int id){
        for (int i=0; i<this.customers.size(); i++) {
            Customer customer = this.customers.get(i);
            if (customer.getId() == id){
                 return customer;
            }
        }
        return null; // no Customer found with this ID; maybe throw an exception
    }
    

    【讨论】:

    • 移出 if 语句不足以修复该方法。您的解决方案是首选。 +1
    【解决方案5】:

    您缺少 return 语句,因为如果您的列表大小为 0,则 for 循环将永远不会执行,因此 if 将永远不会运行,因此您将永远不会返回。

    将 if 语句移出循环。

    【讨论】:

      【解决方案6】:

      即使这个话题已经很老了,我还是想补充一点。 如果您为您的课程覆盖equals,那么它会比较您的getId,您可以使用:

      customer = new Customer(id);
      customers.get(customers.indexOf(customer));
      

      当然,您必须检查IndexOutOfBounds-Exception,它可能被转换为空指针或自定义CustomerNotFoundException

      【讨论】:

        【解决方案7】:

        在 Java 8 中:

        Customer findCustomerByid(int id) {
            return this.customers.stream()
                .filter(customer -> customer.getId().equals(id))
                .findFirst().get();
        }
        

        将返回类型更改为Optional&lt;Customer&gt; 可能会更好。

        【讨论】:

          【解决方案8】:

          我做了类似的事情,编译器看到你的 return 语句在 If() 语句中。如果您希望解决此错误,只需在 If 语句之前创建一个名为 customerId 的新局部变量,然后在 if 语句内分配一个值。在 if 语句之后,调用您的 return 语句,并返回 cstomerId。 像这样:

          Customer findCustomerByid(int id)
          {
              boolean exist=false;
          
              if(this.customers.isEmpty()) {
                  return null;
              }
          
              for(int i=0;i<this.customers.size();i++) {
                  if(this.customers.get(i).getId() == id) {
                      exist=true;
                      break;
                  }
          
                  int customerId;
          
                  if(exist) {
                      customerId = this.customers.get(id);
                  } else {
                      customerId = this.customers.get(id);
                  }
              }
              return customerId;
          }
          

          【讨论】:

            猜你喜欢
            • 2015-01-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-05-27
            • 2016-01-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多