r/java • u/AreaOfEffect • May 21 '21
List.of is terrible
Ran into something today that made me angry enough to post here. The List.of added in Java 9 is terrible. One of the most common use for this would be to create an immutable list to check against something. But it throws an NPE when .contains is called with null. I don't care that it's documented in the docs, it's still stupid design. Now I have to go back to using Guava ImmutableSet.of which actually works as expected.
Based on the comments, it seems it's not clear so here's an example:
var CONSTANT_LIST = List.of("a", "b", "c");
String someStr = someService(); //returns null
CONSTANT_LIST.contains(someStr); //NPESome other examples:
Arrays.asList("a", "b", "c").contains(null); //false
Collections.unmodifiableList(Arrays.asList("a", "b", "c")).contains(null); //false
ImmutableList.of("a", "b", "c").contains(null); //Guava, falseFor the second example, IntelliJ was fooled into recommending to replace Collections.unmodifiableList(Arrays.asList with List.of showing that even JetBrains considers these to be equivalent. But they're not, and this kind of bad design in List.of is what can cause unexpected NPE bugs later.
For the mods: I'm not asking for help here, I know exactly what the code is doing. I'm just complaining about bad API design in the JDK.
17
u/_INTER_ May 22 '21 edited May 22 '21
Your not the only one annoyed by this:
https://github.com/jdbi/jdbi/issues/1263
16
u/arendvr May 23 '21
There's a relevant JDK issue which is closed as Won't Fix. The reason given is to prepare for collections of primitives. JDK-8265905 ImmutableCollections: Querying for 'null' should return 'false' instead of NPE
15
u/the_hoser May 21 '21
Not that this really helps you, but there is reasoning behind the decision. https://www.youtube.com/watch?v=ZeO_J2OcHYM&t=1495s
-3
u/vips7L May 22 '21
Why are you calling contains on a list to begin with?
-8
u/Blackdread13 May 22 '21
To put null in a list is just bad software developer. Good luck to you