Trey Balut
Trey Balut

Reputation: 1395

For Loop with doubles and arrays and Lists

What is the correct syntax to iterate through an array of doubles and add the weights to the values List? The following fails, I've tried all types of combinations but the correct one?

private double[] weightArray =new double[] {200,215,220,215,200};

  List<double[]> values = new ArrayList<double[]>();

  for (int i = 0; i < weightArray.length; i++) {  // i indexes each element successively.
    values.addAll(new double[] weightArray[i]);     
}

TIA

Here is an edit and some additional information. I appreciate all of the answers, my apologies for not clearly stating the question. Below is working code. (Android chart rendering...)

  List<double[]> values = new ArrayList<double[]>();

values.add(new double[] {15,15,13,16.8,20.4,24.4,26.4,26.1,23.6,20.3 });
values.add(new double[] { 10, 10, 12, 15, 20, 24, 26, 26, 23, 18 });
values.add(new double[] { 5, 5.3, 8, 12, 17, 22, 24.2, 24, 19, 15 });
values.add(new double[] { 5, 5, 5, 5, 19, 23, 26, 25, 22, 18});

I want to load these values from a database. They are hard coded in my example. How do I fill the required arrays with numbers? i.e. How do you fill the values.add method using either a for loop or a foreach loop?

The values List is used in the following signature:

Intent intent = ChartFactory.getLineChartIntent(context, buildDataset(titles, x, values),
    renderer, "Test Chart");

TIA

Upvotes: 0

Views: 693

Answers (3)

Jeremy D
Jeremy D

Reputation: 4855

My solution :

Double[] weightArray = {200d, 215d, 220d, 215d, 200d};
List<Double> values = new ArrayList<Double>();

for(Double d : weightArray)  values.add(d);

Best,

Upvotes: 2

Fabian Barney
Fabian Barney

Reputation: 14549

When I understand you right, then you want your Double[] as List<Double>.

Double[] weightArray = {200d, 215d, 220d, 215d, 200d};
List<Double> values = Arrays.asList(weightArray);

Upvotes: 2

user623879
user623879

Reputation: 4142

What I think you are trying to do is this:

private double[] weightArray =new double[] {200,215,220,215,200};

  List<double> values = new ArrayList<double>();

  for (int i = 0; i < weightArray.length; i++) {  // i indexes each element successively.
    values.add(weightArray[i]);     
}

Upvotes: 0

Related Questions