Could someone explain what is causing the NPE in the following example code. It seems to be something to do with how static fields (in particular the Predicate) are initialized maybe, but I can't quite figure out what is going on.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Foo {
public static List<Integer> stuff = doStuff();
private static Predicate<Integer> bar = i -> i == 42;
public static int howBigIsStuff(){
return stuff.size();
}
private static List<Integer> doStuff(){
// java.lang.NullPointerException
// at java.util.Objects.requireNonNull(Objects.java:203)
List<Integer> foo = Arrays.asList(1,2,42,42).stream()
.filter(bar)
.collect(Collectors.toList());
return foo;
}
}
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Test;
public class FooTest {
private static Predicate<Integer> bar = i -> i == 42;
@Test
public void test() {
// This is fine
List<Integer> foo = Arrays.asList(1,2,42,42).stream()
.filter(bar)
.collect(Collectors.toList());
System.out.println(foo); // [42, 42]
Foo.howBigIsStuff();
}
}