Shubham Sharma
Shubham Sharma

Reputation: 11

Exception in ArrayList in java

public static int getMin(int[] arr, int min,int max,int a){
    Integer[] test = Arrays.stream(arr).boxed().toArray(Integer[]::new);
    List<Integer> list =null;
    list = new ArrayList(Arrays.asList(test));
    list.removeAll(Collections.singleton(0));
    min = Collections.min(list);
    max = Collections.max(list);

    if(a == 0) {
        return min;
    } else {
        return max;
    }
}

List item

Exception in thread "main" java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:862)
    at java.util.Collections.min(Collections.java:596)
    at Solution.getMin(Solution.java:47)

What is the reason for this exception?

Upvotes: 1

Views: 507

Answers (2)

djm.im
djm.im

Reputation: 3323

You passed an array that contains only zeros. And this line of code removes all zero elements list.removeAll(Collections.singleton(0));. After this, the list has size zero - no any elements in it.


Here is an example to reproduce the exception

private static void getMin() {
    List<Integer> list = new ArrayList<>();

    Collections.min(list);
}

Upvotes: 1

Basil Bourque
Basil Bourque

Reputation: 338346

Empty collection

The Javadoc for Collections.min states that passing an empty collection will throw a NoSuchElementException.

Add a test for List::isEmpty before checking the minimum and maximum.

Upvotes: 1

Related Questions