Store data in an ArrayList

2

Given the following code:

    int x=0;
    int y=0;
    ArrayList<Point> casilla = new ArrayList<>();
    Point punto = new Point(x, y);
    //Plantilla
    for(int n=0; n<20; n++){
        for(int m=0; m<20; m++) {
            punto.set(x,y);
            casilla.add(punto);
            x = x + 1;
            Log.d("Casilla:", punto + "");
        }
        x = 0;
        y = y + 1;
    }

    for (int i=0;i<200;i++){
        punto = casilla.get(i);
        Log.d("Casilla:", punto + "");
    }

When I try to recover the data the array is only filled with the last value of the loop. Can not store values in a nested loop?

    
asked by M.J.D 06.12.2017 в 13:03
source

2 answers

4

You are adding the same instance of the point object to ArrayList , so it will update all the elements you add to the list:

//...
Point punto = new Point(x, y);
for(int n=0; n<20; n++){
    for(int m=0; m<20; m++) {
        // se esta utilizando la misma instancia por lo que siempre agregaras el mismo
        // objeto a la lista y todos los valores seran los mismos
        punto.set(x,y);
        casilla.add(punto);

You must initialize an instance of the Point class within the for, not outside, so that it is independent of the other instances and does not update all:

///...
for(int n=0; n<20; n++){
    for(int m=0; m<20; m++) {
        // iniciamos una nueva instancia de Point
        Point punto = new Point(x, y);
        punto.set(x,y);
        casilla.add(punto);

        //...
    
answered by 06.12.2017 / 13:35
source
-1

In each loop you must add a new instance of Point to your ArrayList , if you create only one the first data will always remain.

You must create a new instance of Point in each loop.

    int x=0;
    int y=0;
    ArrayList<Point> casilla = new ArrayList<>();
    Point punto = new Point(x, y);
    //Plantilla
    for(int n=0; n<20; n++){
        for(int m=0; m<20; m++) {

             //*Crea instancia de punto para un nuevo dato!
            punto = new Point(x, y); 

            //agrega datos a punto.
            punto.set(x,y);
            //Agrega nuevo punto a ArrayList.
            casilla.add(punto);
            x = x + 1;
            Log.d("Casilla:", punto + "");
        }
        x = 0;
        y = y + 1;
    }

    //Imprime datos almacenados
    for (int i=0;i<200;i++){
        punto = casilla.get(i);
        Log.d("Casilla:", punto + "");
    }
    
answered by 06.12.2017 в 18:08