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

发布于 2024-08-24 11:31:53 字数 278 浏览 3 评论 0原文

我的代码如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

離殇 2024-08-31 11:31:53
Collections.addAll(myVector, myArray);

这是将数组内容添加到集合(例如向量)中的首选方法。

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

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

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

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.

℉絮湮 2024-08-31 11:31:53

vector.addAll() 在参数中采用 Collection。
为了将数组转换为 Collection,您可以使用 Arrays.asList():

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

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

My_Vector.addAll(Arrays.asList(My_Array));
淡紫姑娘! 2024-08-31 11:31:53
My_Vector.addAll(Arrays.asList(My_Array));

如果您注意到, Collection.addAll 采用 Collection 参数。 Java 数组不是 Collection,而是 Arrays.asList,与 Collection.toArray,是“基于数组和集合之间的桥梁”基于API”。

或者,为了将数组中的元素添加到 Collection 的特定目的,您还可以使用静态帮助器方法 addAll 来自 <代码>集合类。

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

If you notice, Collection.addAll takes a Collection argument. 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".

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

Collections.addAll(My_Vector, My_Array);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文