How to quickly and conveniently create a one element arraylist
This question already has an answer here:
Fixed size List
The easiest way, that I know of, is to create a fixed-size single element List
with Arrays.asList(T...)
like
// Returns a List backed by a varargs T.
return Arrays.asList(s);
Variable size List
If it needs vary in size you can construct an ArrayList
and the fixed-size List
like
return new ArrayList<String>(Arrays.asList(s));
and (in Java 7+) you can use the diamond operator <>
to make it
return new ArrayList<>(Arrays.asList(s));
Collections.singletonList(object)
You can use the utility method Arrays.asList
and feed that result into a new ArrayList
.
List<String> list = new ArrayList<String>(Arrays.asList(s));
Other options:
List<String> list = new ArrayList<String>(Collections.nCopies(1, s));
and
List<String> list = new ArrayList<String>(Collections.singletonList(s));
ArrayList(Collection)
constructor. Arrays.asList
method. Collections.nCopies
method. Collections.singletonList
method. With Java 7+, you may use the "diamond operator", replacing new ArrayList<String>(...)
with new ArrayList<>(...)
.
Java 9
If you're using Java 9+, you can use the List.of
method:
List<String> list = new ArrayList<>(List.of(s));
Regardless of the use of each option above, you may choose not to use the new ArrayList<>()
wrapper if you don't need your list to be mutable.
上一篇: 如何声明一个ArrayList的值?
下一篇: 如何快速方便地创建一个元素数组列表