如何将字符串数组中的所有项目添加到 Java 中的向量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2383620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:49:05  来源:igfitidea点击:

How to add all items in a String array to a vector in Java?

javastringarraysvectoradd

提问by Frank

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

坦率

采纳答案by Yannick Loriot

The vector.addAll()takes a Collection in parameter. In order to convert array to Collection, you can use Arrays.asList():

vector.addAll() 在参数中接受一个集合。为了将数组转换为集合,您可以使用 Arrays.asList():

My_Vector.addAll(Arrays.asList(My_Array));

回答by polygenelubricants

My_Vector.addAll(Arrays.asList(My_Array));

If you notice, Collection.addAlltakes a Collectionargument. A Java array is not a Collection, but Arrays.asList, in combination with Collection.toArray, is the "bridge between array-based and collection-based APIs".

如果您注意到,Collection.addAll则进行Collection论证。Java 数组不是Collection,而是Arrays.asList与 结合使用Collection.toArray,是“基于数组和基于集合的 API 之间的桥梁”。

Alternatively, for the specific purpose of adding elements from an array to a Collection, you can also use the static helper method addAllfrom the Collectionsclass.

可替代地,用于将来自一个数组元素到的具体目的Collection,还可以使用静态辅助方法addAllCollections类。

Collections.addAll(My_Vector, My_Array);

回答by Chris Jester-Young

Collections.addAll(myVector, myArray);

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...-

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#addAll-java.util.Collection-T...-

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

将所有指定的元素添加到指定的集合。要添加的元素可以单独指定或作为数组指定。此便捷方法的行为与 c.addAll(Arrays.asList(elements)) 的行为相同,但在大多数实现中,此方法的运行速度可能明显更快。