【问题标题】:Converting foreach loop to a while loop将 foreach 循环转换为 while 循环
【发布时间】:2014-12-11 01:58:13
【问题描述】:

所以这是我需要帮助转换的循环:

public Product findProduct(int id) {

    Product found = null;
    for(Product m : stock){
        if(m.getID() == id){
            found = m;
        }
    }
    return found;
}

它应该搜索 stock 集合(我刚开始学习,所以我不太了解这些术语),以查找具有与我们在方法中输入的 int 值相同的 ID 字段的 Product 对象。 我想到了一个while循环,我想我有点理解它。我没有得到的是我应该如何获得 m.getID() 的值,即 Product 类中的 ID 字段。 该类不允许有 import.java.util.Iterator

【问题讨论】:

  • 使用 iterator.next() 时需要对元素进行强制转换。例如:产品 m = (Product) productIterator.next()
  • 我认为没有理由因为这个原因而进行一段时间的循环。老实说,我只是在found = m; 之后添加一个break;,以避免在您已经找到所需内容之后进行不必要的迭代。
  • .. 或者在找到匹配项时只使用return m,然后在循环完成后使用return null 而不是return found

标签: java loops foreach while-loop


【解决方案1】:

相当简单,这意味着返回的 Product 对象(如果它不为 null)将具有可通过 getID() 方法访问的 id 值:

public Product findProduct(int id) {

    for(Product m : stock) {
        if(m.getID() == id){
            return m;
        }
    }
    return null;
}

【讨论】:

  • 虽然这可行,但它与 OP 已有的并没有什么不同,也没有解决 OP 的问题:/
  • OP的问题是什么?我不确定。你能解释一下吗?
【解决方案2】:
Product found = null;
int counter = 0;
while(counter < stock.size())
{
   if(stock.get(i).getID() == id)
   {
       found = stock.get(i).getID();
       break;
   }
   counter++;
}

这将使用 while 循环遍历您的列表,并在找到元素时退出循环。休息;用于在找到元素时跳出循环。查看 while 循环的语法并尝试弄清楚它是如何工作的。

【讨论】:

    【解决方案3】:

    如果您想使用while 循环,请使用get(...) 方法遍历每个项目:

    public Product findProduct(int id) {
        int counter = 0;
        while(counter < stock.size())
        {
           if(stock.get(counter) != null && stock.get(counter).getID() == id)
               return stock.get(counter);
           counter++;
        }
        return null;
    }
    

    确保在使用.get(...) 方法时进行null 检查。

    带有for 循环的替代选项:

    public Product findProduct(int id) {
        for(int i = 0; i< stock.size(); i++)
           if(stock.get(i) != null && stock.get(i).getID() == id)
               return stock.get(i);
    
        return null;
    }
    

    注意:根据Product 类的编写方式,您可能需要在此处使用.equals(...) 而不是==

    那么当你调用方法时:

    int id = //whatever
    Product product = findProduct(id);
    
    int newId;
    if(product != null)
        newId = product.getID();//should be same as id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 2017-04-26
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多