gpt4 book ai didi

java - 构造函数中的ArrayList

转载 作者:行者123 更新时间:2023-12-01 18:42:37 25 4
gpt4 key购买 nike

我正在尝试在构造函数中从该实例中的 arrayList 添加值而不是静态值:

构造函数中具有静态值的实例

v0.adjacencies = new Edge[]{ new Edge(v1,  79.83),
new Edge(v5, 81.15) };

我想用数组元素替换这些值。例如:

v0.adjacencies = new Edge[]{ VALUES FROM ArrayList (ar2edge) };

我从中得到数组

for (int kk=0;kk<arvertex.size();kk++){
Edge edges = new Edge(arvertex.get(kk),ar2.get(kk));
ar2edge.add(edges);
}

最佳答案

使用toArray() method返回 ArrayList 元素的数组。

Edge[] edges = ar2edge.toArray(new Edge[ar2edge.size()]);

引用上面链接的 Javadocs:

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

这样,您就可以声明自己的适当大小的数组,并且 toArray 会为您填充它。

关于java - 构造函数中的ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19306425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com