List.of() vs Collections.emptyList() which one is better?
List.of() and Collections.emptyList() both return an empty list. If we want to simply return an empty list we can use any one of them.
Collections.emptyList() is out there for quite a long time but List.of() is fairly new. List.of() was introduced in Java 1.9 version. Collections.emptyList() has became the well adopted among developers but hopefully List.of() will also become well accepted by all.
Following are some differences between List.of() and Collections.emptyList().
List.of() | Collections.emptyList() |
List.of() is shorter | Collections.emptyList() expresses itself |
Provide immutable list | Provide immutable list |
List is NOT serializable | List is serializable |
Cast the collection object to the List object and return | Cast the collection object to the List object and return |
If contains(obj) method is used then it will throw null pointer exception | If contains(obj) method is used then it will return false |