本文介绍了LinkedList:抛出NoSuchElementException的Collections.max()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有通过扫描仪或其他方法来迭代 LinkedList ,而是使用 Collections.max()可以从 LinkedList 中获取最大数量。

I am not iterating the LinkedList by any means like scanner or other methods, I am using Collections.max() to get maximum number from the LinkedList.

我在Stack Overflow上已经读到,由于该异常而引发

I have read on Stack Overflow that this exception is thrown due to iterator or scanner or tokenizer, but I am using none of them.

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<Integer> first = new LinkedList<Integer>();
        LinkedList<Integer> second = new LinkedList<Integer>();

        int cases = Integer.parseInt(br.readLine());

        for(int i=1;i<=cases;i++) {
            String score = br.readLine();
            int number1 = Integer.parseInt(score.split(" ")[0]);
            int number2 = Integer.parseInt(score.split(" ")[1]);
            int diff = number1 - number2;

            if(diff > 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
 * <i>natural ordering</i> of its elements.  All elements in the
 * collection must implement the <tt>Comparable</tt> interface.
 * Furthermore, all elements in the collection must be <i>mutually
 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a
 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
 * <tt>e2</tt> in the collection).<p>
 *
 * 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 <i>natural ordering</i> of its elements.
 * @throws ClassCastException if the collection contains elements that are
 *         not <i>mutually comparable</i> (for example, strings and
 *         integers).
 * @throws NoSuchElementException if the collection is empty. <---------------
 * @see Comparable
 */
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

这篇关于LinkedList:抛出NoSuchElementException的Collections.max()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 07:35