关于java:我如何从ArrayList< String>转换

How can i convert from ArrayList<String> to double[]?

本问题已经有最佳答案,请猛点这里访问。

我有一个这样的阵列列表:

1
[5, 181, 138, 95, 136, 179]

我想做的是将这个列表转换为double[]。像这样。

1
double[] Fails = new double[]{5, 181, 138, 95, 136, 179};

这是我的代码:

1
2
3
4
5
6
7
8
9
10
    ArrayList<String> DatesList = new ArrayList<String>();
    ArrayList<String> FailList = new ArrayList<String>();


    while (rs2.next()) {
        DatesList.add(rs2.getString("Date"));
        FailList.add(rs2.getString("fail"));
    }

    double[] Fails = new double[]{FailList}; //obviously it doesn't work..

有没有办法把arraylist转换成double[]?


1
2
3
4
5
6
7
8
9
10
11
List<String> failList = new ArrayList<>();

while (rs2.next()) {        //whatever that is (copied from OP)
    failList.add(rs2.getString("fail"));
}

double[] failsArray = new double[failList.size()]; //create an array with the size of the failList

for (int i = 0; i < failList.size(); ++i) { //iterate over the elements of the list
    failsArray[i] = Double.parseDouble(failList.get(i)); //store each element as a double in the array
}

这段代码的作用是,它首先创建一个数组failsArray,大小为failList。然后,它迭代failList并将每个项解析为double,并将其存储在failsArray中。