LinkedList:Collections.max()抛出NoSuchElementException

我不是通过扫描仪或其他方法迭代LinkedList ,我使用Collections.max()LinkedList获取最大数量。

我已经在Stack Overflow上读到由于迭代器或扫描器或标记器而引发此exception,但我没有使用它们。

 import java.io.*; import java.util.*; class TLG { public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); LinkedList first = new LinkedList(); LinkedList second = new LinkedList(); int cases = Integer.parseInt(br.readLine()); for(int i=1;i 0){ first.add(diff); } else { second.add(java.lang.Math.abs(diff)); } } Integer max1 = Collections.max(first); // Getting Exception here Integer max2 = Collections.max(second); // Getting Exception here if(max1 > max2) { System.out.println(1+" "+max1); } else { System.out.println(2+" "+max2); } } } 

 /** * Returns the maximum element of the given collection, according to the * natural ordering of its elements. All elements in the * collection must implement the Comparable interface. * Furthermore, all elements in the collection must be mutually * comparable (that is, e1.compareTo(e2) must not throw a * ClassCastException for any elements e1 and * e2 in the collection).

* * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param coll the collection whose maximum element is to be determined. * @return the maximum element of the given collection, according * to the natural ordering of its elements. * @throws ClassCastException if the collection contains elements that are * not mutually comparable (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. <--------------- * @see Comparable */ public static > T max(Collection coll)

你用空列表调用Collections.max()。

您没有检查Empty case:所以Collections.max()将抛出NoSuchElementException

首先检查任何列表是否为空(然后您知道最大值和列表提供它)

  Integer max; int list; if (first.isEmpty()) { max = Collections.max(second); list = 2; } else if (second.isEmpty()) { max = Collections.max(first); list = 1; } else { Integer max1 = Collections.max(first); Integer max2 = Collections.max(second); if (max1 > max2) { max = max1; list = 1; } else { max = max2; list = 2; } } System.out.println(list + " " + max);