如何将字符串数组中的所有项目添加到 Java 中的向量中?
我的代码如下所示:
Vector<String> My_Vector=new Vector<String>();
String My_Array[]=new String[100];
for (int i=0;i<100;i++) My_Array[i]="Item_"+i;
......
My_Vector.addAll(My_Array);
但是我收到一条错误消息,在不循环添加每个项目的情况下,正确的方法是什么?
坦率
My code looks like this :
Vector<String> My_Vector=new Vector<String>();
String My_Array[]=new String[100];
for (int i=0;i<100;i++) My_Array[i]="Item_"+i;
......
My_Vector.addAll(My_Array);
But I got an error message, what's the right way to do it, without looping to add each item ?
Frank
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是将数组内容添加到集合(例如向量)中的首选方法。
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#addAll-java.util.Collection-T...-
This is the preferred way to add the contents of an array into a collection (such as a vector).
https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#addAll-java.util.Collection-T...-
vector.addAll() 在参数中采用 Collection。
为了将数组转换为 Collection,您可以使用 Arrays.asList():
The vector.addAll()takes a Collection in parameter.
In order to convert array to Collection, you can use Arrays.asList():
如果您注意到,
Collection.addAll
采用Collection
参数。 Java 数组不是Collection
,而是Arrays.asList
,与Collection.toArray
,是“基于数组和集合之间的桥梁”基于API”。或者,为了将数组中的元素添加到
Collection
的特定目的,您还可以使用静态帮助器方法addAll
来自 <代码>集合类。If you notice,
Collection.addAll
takes aCollection
argument. A Java array is not aCollection
, butArrays.asList
, in combination withCollection.toArray
, is the "bridge between array-based and collection-based APIs".Alternatively, for the specific purpose of adding elements from an array to a
Collection
, you can also use the static helper methodaddAll
from theCollections
class.