Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections max NullPointerException

I have java 1.8.0_171 and the following code in DataUtils.java class:

List<BigDecimal> list = new ArrayList<>();
list.add(new BigDecimal(0));
list.add(new BigDecimal(-2));
list.add(new BigDecimal(10));
list.add(new BigDecimal(200));

if ((Collections.max(list).subtract(Collections.min(list)).compareTo(new BigDecimal(0)) != 0)) {
    .....
            } 

And I have the following exception:

Exception in thread "main" java.lang.NullPointerException at java.util.Collections.max(Unknown Source) at com.util.DataUtils.calculateRetsentindex(DataUtils.java:23)

The default jdk is set on Eclipse correctly, clean-rebuild don't fix. Please, advice


1 Answers

This means that in your collection you probably have added a null element. In your example:

 List<BigDecimal> list = new ArrayList<>();
          list.add(new BigDecimal(0));
          list.add(new BigDecimal(-2));
          list.add(new BigDecimal(10));
          list.add(new BigDecimal(200));
          if ((Collections.max(list).subtract(Collections.min(list)).compareTo(new BigDecimal(0)) != 0)) {
                System.out.println("OK");
          } 

It prints "OK" properly. If you change the first object to null though:

list.add(null);

You get similar exception to yours.

And if you do Collections.max(null); you get the exact same exception. So I guess your list is not initialized when you do the call.

like image 81
Veselin Davidov Avatar answered Oct 21 '25 12:10

Veselin Davidov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!