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[]?

7
  • 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. Commented Nov 5, 2014 at 14:56
  • @JeroenVannevel if marked as duplicate, at least include a link.... Commented Nov 5, 2014 at 14:57
  • 1
    @JeroenVannevel I don't think it is duplicate ! and should be reopened ! Commented Nov 5, 2014 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 Commented Nov 5, 2014 at 15:00
  • 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. Commented Nov 6, 2014 at 8:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.