How do I set an empty list of a certain type
We have Collections.EMPTY_LIST
but 开发者_C百科it is not typed, which shows an eclipse warning. How do I set an empty list of a certain type.
Try this
Collections.<String> emptyList();
See this also Type-safe, generic, empty Collections with static generics
To get an empty List
of String
for example:
List<String> list = Collections.<String>emptyList();
Use Collections.emptyList(); You can check the jdk document for it.
Since Java 10: use var keyword and List.of()
Disclaimer: this will give you a List<Object>
. If you want a typed List, you should not use the keyword var
for an empty list. But note that var list = List.of("hello", "world");
will give you a typed list, but not empty.
In Java 10, var keyword was introduced to allow local variable type inference. In other words the type for the local variable will be inferred by the compiler, so the developer does not need to declare it.
Hence, you can use the following statement to create an empty list:
var list = List.of() // since Java 10, use the var keyword, List.of() was introduced in Java 9.
Since Java 9: use List.of()
Since Java 9, there is the convenient List.of() static factory methods, that provide a convenient way to create immutable lists. Example:
List<String> list = list.of();
The List instances created by these methods have the following characteristics:
- structurally immutable: elements cannot be added, removed, or replaced. Otherwise the
UnsupportedOperationException
is thrown. - disallow null elements. Otherwise
NullPointerException
is thrown. - serializable if all elements are serializable.
- ... see JavaDoc
Prior to Java 9: use Collections. emptyList()
The convenient method emptyList() returns an empty list (immutable). This list is serializable. JavaDoc
List<String> list = Collections.<String> emptyList(); // prior Java 9
Note that Collections.<String> emptyList()
returns the constant : EMPTY_LIST
To call List.of()
while specifying a type, use List.<Class>of()
, for example:
List.<String>of()
You could also use one of these:
new ArrayList<String>()
Arrays.asList("item of the specific type")
Use
Collections.<Type>emptyList();
where Type
is the type you want to type cast the list to.
精彩评论