如何从ArrayList <string>转换为double []?</string>

时间:2014-11-05 14:51:30

标签: java arraylist double

我有一个像这样的ArrayList:

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

我想做的是将此列表转换为double []。这样的事情。

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

这是我的代码:

    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 个答案:

答案 0 :(得分:4)

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中。