将值添加到数组列表
问题描述:
所以我打算给一个数组列表(PolyArr)添加5个随机数。我只是Java的初学者,不太了解语法。你能告诉我如何正确地格式化我的最后一行吗?将值添加到数组列表
'package ga1;
import java.util.*;
import java.lang.Math;
public class GA1 {
static int k=5;
public static void main(String[] args) {
double a;
List<Double[]> PolyArr= new ArrayList<>(k);//Creating the arraylist
for (int i=0; i<k; i++){
a = Math.random() * 50;
//PolyArr.add(new Double() {a});
}
}
}'
答
您试图创建一个大小为5的数组与5随机?使用此:
List<Double> polyArr= new ArrayList<>(k);//Creating the arraylist
for (int i=0; i<k; i++){
double a = Math.random() * 50; // random
polyArr.add(a);
}
注:请不要使用大写在Java属性,只为类名和静态字段
通过这种新的双[] {A}你创建一个doulbes的阵列,大小为1,内有1个随机数
答
您需要首先创建数组并将其添加到数组中,然后您可以将数组添加到列表中。但是你真的需要这个阵列吗?你不能直接添加双重名单?
import java.util.*;
import java.lang.Math;
public class GA1 {
static int k=5;
public static void main(String[] args) {
double a;
List<Double[]> PolyArr= new ArrayList<>(k);//Creating the arraylist
Double[] randNums = new Double[k]; //create the double array first based on k
for (int i=0; i<k; i++){
randNums[i] = Math.random() * 50; // add to array
}
PolyArr.add(randNums); // then add to the list
}
}
答
PolyArr.add(new Double() {a});
的事情是你无法创建final类的子类。这是你试图在上面做的事情。如果你在IDE中试过,你可能会注意到:
An anonymous class cannot subclass the final class Double
我不知道这是什么目的..可能是你正在处理。无论如何,这是很好的为你明白发生了什么,你可以这样做也:
double a[] = new double[k];
List<Double> PolyArr= new ArrayList<>(k);//Creating the arraylist
for (int i=0; i<k; i++){
a[i] = Math.random() * 50;
PolyArr.add(new Double(a[i]));
}
for(double i : PolyArr){
System.out.println(i);
}
您也可以尝试这样的:
double a;
List<Double[]> PolyArr= new ArrayList<>(k);//Creating the arraylist
for (int i=0; i<k; i++){
a = Math.random() * 50;
Double he[] = {a};
PolyArr.add(he);
}
for(Double[] i : PolyArr){
for(Double y : i)
System.out.println(y);
}
这可能不是你所期待的。然而,尝试每一个答案。
https://*.com/questions/10797034/adding-values-to-arraylist –
@CharlieNg我不明白这是如何帮助! – niceman
史蒂夫,你应该改变标题为'添加阵列值数组arrays' :) – niceman