1

I am trying to assign adjused values to the ArrayList adjustedValues, and would need that estimatedValues do not change after the adjustValues() method is called in main.

I have attempted to use inside the adjustValues() method:

ArrayList<ArrayList<Double>> adjustedValues = (ArrayList< ArrayList< Double>>) estimatedValues.clone();

but had no luck since the elements which I needed were still getting modified

import java.util.ArrayList;

public class Test123 {

    public static void main(String[] args) {

        ArrayList<ArrayList<Double>> initialWeight = generateRandomWeights(6,0.1, 1);
        ArrayList<ArrayList<Double>> estimatedValues = generateRandomWeights(6,0.1, 1);

        ArrayList<ArrayList<Double>> adjustedValues = adjustValues(initialWeight, estimatedValues);
    }


    public static ArrayList<ArrayList<Double>> adjustValues (ArrayList<ArrayList<Double>> weights, ArrayList<ArrayList<Double>> estimateValues){

        ArrayList<ArrayList<Double>> adjustedValues = new ArrayList<>(estimateValues);


        for(int i=0; i<estimateValues.size(); i++){
            for(int j=0; j<estimateValues.get(i).size(); j++){
                adjustedValues.get(i).set(j, estimateValues.get(i).get(j) * weights.get(i).get(j));


            }
        }

        return adjustedValues;
    }

    public static ArrayList<Double> getArrayListOfRandom(int c,double min, double max){
        ArrayList randomValues = new ArrayList();

        for(int i=0;i< c; i++){
            double x = ((Math.random() * (max - min)) + min);
            randomValues.add(x);
        }


        return randomValues;
    }

    public static ArrayList<ArrayList<Double>> generateRandomWeights(int c, double min, double max){
        ArrayList<ArrayList<Double>> weights = new ArrayList<>();


        for(int i=0; i<c; i++){
            weights.add(getArrayListOfRandom(c,min,max));
        }

        return weights;
    }


}

Enlico
  • 23,259
  • 6
  • 48
  • 102

1 Answers1

0

ArrayList.clone and the copy constructor both create a shallow copy of the initial arraylist. This would work fine if it were a list of primitives, but your list contains other lists so a shallow copy means they are still mutable(contents can be changed). A few ways to do a deep copy are discussed on this question. java: best way to do deep copy of list of lists

Thomas
  • 5,074
  • 1
  • 16
  • 12