jdfinch3 jdfinch3 - 14 days ago 5
Java Question

Java - How can I avoid re-using a variable that represents a computation created in a loop that needs to be added to a list?

Alternative question: How can I re-use a variable without the value of the first use (that has been added to a list) being changed?

Instead of a long explanation, I'll just post some code, which should explain what I'm trying to do and demonstrate my problem.

public class Test
{
static ArrayList<Double> totallist = new ArrayList<Double>();
static ArrayList<Double> inputlist = new ArrayList<Double>();
static ArrayList<ArrayList<Double>> outputlist = new ArrayList<ArrayList<Double>>(); //ArrayList of Arraylists
static double total;

public void test()
{
//the numbers aren't important, just examples
inputlist.add(5);
inputlist.add(3.8);
inputlist.add(1.9);
inputlist.add(.8);
inputlist.add(4.1);

outputlist.get(0).add(9);
outputlist.get(0).add(5.9);
outputlist.get(0).add(4);
outputlist.get(0).add(2.88);
outputlist.get(0).add(5.6);
outputlist.get(1).add(3);
//...etc until outputlist has 5 ArrayLists each with 5 doubles

//I need to multiply each of the 5 inputs by each output in each
//internal ArrayList and then enter the sum of those
//multiplications into totallist

for (int i = 0; i < 5; i++) {
total = 0;
for (int i2 = 0; i2 < 5; i2++) {
double input = inputlist.get(i);
double output = outputlist.get(i).get(i2);
total += input * output;
}
totallist.add(total);
}

}
}


As you can see, the problem is the variable
total
, which is getting reset each time the first for loop iterates. So the end result of the ArrayList
totallist
is 5 entries of the last i loop iteration instead of 5 entries of the result of each i loop iteration.

I can't figure out a way around this that doesn't involve a huge amount of variables and loops... There has to be something I'm missing.

EJP EJP
Answer

There is no problem here to solve. The total variable gets auto-boxed to a Double object before being added to the list. You can reuse total to your heart's content.

However it should certainly be a local variable, not static.