简体   繁体   English

在集合中寻找最小值

[英]Finding minimum value in a collection

To find the minimum value in a collection of given types, what would I need to set "value" to in order to compare it to "min"? 要在给定类型的集合中找到最小值,我需要将“ value”设置为什么才能将其与“ min”进行比较? Value should be the next element in the collection and it should iterate until the collection is fully read through. 值应该是集合中的下一个元素,并且应该迭代直到完全读取了集合。

public <T> T min(Collection<T> c, Comparator<T> comp) {
if ((c == null) || (comp == null)) {
     throw new IllegalArgumentException();
  }

  if (c.isEmpty() == true) {
     throw new NoSuchElementException();
  }

  Iterator itr = c.iterator(); 
  T min = (T)itr.next();
  T value = ;
  while (itr.hasNext()) {   
     if (comp.compare(min, value) < 0) { 
        min = value;  
     }
  }
  return min;

} }

Use the following code: 使用以下代码:

 Iterator itr = c.iterator(); 
 T min = (T)itr.next();
 T value;
 while (itr.hasNext()) { 
      value=(T)itr.next();
      if (comp.compare(min, value) < 0) { 
         min = value;  
      }
 }

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

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