java - 查找数组列表中的最小值

标签 java arraylist

我正在尝试查找数组列表(iList)中的最小值。数组列表包含多个项目(InventoryItem),每个项目都有自己的描述、成本等。我需要找到最小的成本,并返回成本最小的项目。另外,我必须使用 while 循环而不是 for 。这是到目前为止我的代码:

public InventoryItem itemWithLowestCost() {

  int index = 0;
  double smallest = 0;

  while (index < iList.size()) {
     if (!(smallest < iList.get(index).getCost())) {
        smallest = iList.get(index).getCost();
     }

     if (iList.get(index).getCost() == smallest) {
        return //what to put here? ;
     }  

     index++; 
  }  

}

最佳答案

这非常简单。存储当前最低的值,迭代,如果有较小的值,则保存它。最后返回当前最小的。

public InventoryItem itemWithLowestCost() {

  InventoryItem smallest = iList.get(0);

  for (int i=1;i<iList.size();i++) {
    if(iList.get(i).getCost() < smallest.getCost()) {
      smallest = iList.get(i);
    }
  }

  return smallest;
}

如果你需要使用 while 循环,那么只需使用一个伪装的 for 循环;)

public InventoryItem itemWithLowestCost() {

  InventoryItem smallest = iList.get(0);

  int i = 1;
  while (i<iList.size()) {
    if(iList.get(i).getCost() < smallest.getCost()) {
      smallest = iList.get(i);
    }
    i++;
  }

  return smallest;
}

关于java - 查找数组列表中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153095/

相关文章:

java - 返回 StringTokenizer 以便能够在 Textarea 上设置 Text

java.lang.ang.NoClassDefFoundError : org/hibernate/util/DTDEntityResolver 错误

arrays - SQL 选择查询的循环结果

java - 如何计算数组中重复元素的重复次数?

java - http 连接错误 java.lang.IllegalArgumentException : Illegal character in query at index 76

java - 使用同步方法测试两个线程递增单个int的结果令人困惑

java - 在vertx api中接受相同键的参数列表

Java - 从两个不同数据类型的 ArrayLists 中获取公共(public)元素

java - 打印二维 ArrayList 矩阵的值

java - 在java中合并两个ArrayList