How to declare an ArrayList with values?
爪哇中的AARAYLIST或LISH声明对如何声明空EDCOX1的0个问题提出了质疑和回答,但如何声明具有值的数组?
我尝试了以下操作,但它返回一个语法错误:
| 1 2 3 4 5 6 7 8 9 | import java.io.IOException; import java.util.ArrayList; public class test { public static void main(String[] args) throws IOException { ArrayList<String> x = new ArrayList<String>(); x = ['xyz', 'abc']; } } | 
在Java 10 +中你可以做到:
| 1 | 
Java 8中使用0:
| 1 | Stream.of("xyz","abc").collect(Collectors.toList()); | 
当然,您可以使用接受
| 1 | 
提示:文档包含非常有用的信息,通常包含您要查找的答案。例如,下面是
- ArrayList() 
 - Constructs an empty list with an initial capacity of ten. 
- ArrayList(Collection extends E> c) ()
 - Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. 
- ArrayList(int initialCapacity) 
 - Constructs an empty list with the specified initial capacity. 
用途:
| 1 | 
如果以后不想向列表中添加新元素,也可以使用(array.aslist返回固定大小的列表):
| 1 | 
注意:如果愿意,也可以使用静态导入,如下所示:
| 1 | 
…
| 1 | List<String> x = new ArrayList<>(asList("xyz","abc")); | 
或
| 1 | List<String> x = asList("xyz","abc"); | 
您可以这样做:
| 1 | 
guava库包含创建列表和其他集合的方便方法,这使得它比使用标准库类更漂亮。
例子:
| 1 | ArrayList<String> list = newArrayList("a","b","c"); | 
(假设为
试试这个!
| 1 | 
如果不需要调用特定的方法,那么使用接口
使用这一个: