0

I have a ArrayList like this:

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

what i wanted to do, is convert this list to double []. Something like this.

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

This is my code:

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

Is there any way to convert from ArrayList to double[]?

Sallyerik
  • 489
  • 2
  • 11
  • 24
  • Loop over it and parse each member as a double. Obviously you can't use the initializer block with a collection, nor can you assign strings to doubles. – Jeroen Vannevel Nov 05 '14 at 14:56
  • @JeroenVannevel if marked as duplicate, at least include a link.... – nafas Nov 05 '14 at 14:57
  • 1
    @JeroenVannevel I don't think it is duplicate ! and should be reopened ! – StackFlowed Nov 05 '14 at 15:00
  • 1
    @JeroenVannevel I mean a proper example, the problem in this question is to convert String to Double. rather than ArrayList to Array – nafas Nov 05 '14 at 15:00
  • For completeness' sake: [how to convert string to double](http://stackoverflow.com/questions/5769669/convert-string-to-double-in-java). Combine this with the question I marked as duplicate. Here at Stack Overflow we expect you to be able to find and apply basic solutions that are all over the web. We also expect you to be able to extrapolate the concrete examples to your specific use case. – Jeroen Vannevel Nov 05 '14 at 15:02
  • @JeroenVannevel thx mate, Just a suggestion --> I think stackoverflow should able to include multiple sources once a question is marked as duplicate. something like . – nafas Nov 05 '14 at 15:06
  • 1
    @JeroenVannevel, @nafas, I think both of you are right. The reference question seems the same as my. The problem is that all the answers are not enough clear for my "shorts knowledge" I miss it ` Double.parseDouble(failList.get(i));` to get my properly double object. But is true, is much better to get your own answer from some suggestion, it gonna made me get better. Thanks anyway both of you. – Sallyerik Nov 06 '14 at 08:45

1 Answers1

6
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
}

What this code does, is that it first creates an array failsArray with the size of the failList. Then, it iterates over the failList and parses each item as double and stores it in the failsArray.

vefthym
  • 7,422
  • 6
  • 32
  • 58