如何与申报值一个ArrayList? [英] How to declare an ArrayList with values?
问题描述
ArrayList中声明的Java 质疑,并回答了如何声明一个空的的ArrayList
但我怎么声明一个ArrayList与价值?
我试过以下,但它返回一个语法错误:
进口java.io.IOException异常;
进口的java.util.ArrayList;公共类的测试{
公共静态无效的主要(字串[] args)抛出IOException
ArrayList的<串GT; X =新的ArrayList<串GT;();
X = ['某某','ABC'];
}
}
您可以使用接受<一个构造函数创建一个新对象href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html\"><$c$c>Collection$c$c>:
列表&LT;串GT; X =新的ArrayList&LT;&GT;(Arrays.asList(XYZ,ABC));
当你有一个像这个问题,你应该访问文档,看看有什么可以构造有:
-
<一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--\"><$c$c>ArrayList()$c$c>
构造一个具有十一个初始容量的空列表。
块引用> -
<一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-\"><$c$c>ArrayList(Collection<?扩展E&GT; C)
构造一个包含指定集合中的元素的列表,它们的顺序依次通过集合的迭代器返回。
块引用> -
<一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-int-\"><$c$c>ArrayList(int参数:initialCapacity)
用指定初始容量的空列表。
块引用>
使用Java的解决方案,8 <一个href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html\"><$c$c>Stream$c$c>:
Stream.of(XYZ,ABC)收集(Collectors.toList());
ArrayList declaration Java has questioned and answered how to declare an empty ArrayList
but how do I declare an arraylist with values?
I've tried the following but it returns a syntax error:
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'];
}
}
You can create a new object using the constructor that accepts a Collection
:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
When you have question like this, you should visit the docs and see what constructors available there:
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.
Java 8 solution using Stream
:
Stream.of("xyz", "abc").collect(Collectors.toList());
这篇关于如何与申报值一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!