Search code examples
javacollectionsjava-8nullpointerexceptionmax

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


Solution

  • 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.