Problems working with arraylist

-1

I have a main class where I load the data into an arrayList and a class called material that I call from the arrayList to load data. The problem is that when loading data from the main class I do not have problems but if from another class I enter data in that class arrayList starts me from scratch. I would like to know how this data will be stored even though I am calling this arrayList from several classes. Because with a database it could be done without problem loading the data but I wanted to take this case to handle arrayList.

Greetings and thanks for your time

    
asked by kiristof 13.09.2016 в 15:23
source

4 answers

0

And if you use a static arrayList ?, it will keep the data until the end of the life cycle of the application you are building.

example:

public static ArrayList<String> list = new ArrayList<String>(); list.add("a");

    
answered by 13.09.2016 в 15:52
0

It may be that when you call your arrayList from the other class you are doing this miArray = new ArrayList(); what you do is create a new instance of it, try stating Static

    
answered by 13.09.2016 в 15:52
0

Obviously the collection will be empty if what you do is create an instance of the class that contains the collection. This happens because when a variable / field / property of a class belongs only to the instance that is created from it, but does not belong "to the class".

By belonging to the class instead of the instance, what would happen is that the collection would be static and would no longer depend on the instance.

public class Store {
    public static final List<Tipo> items = new ArrayList<>();
}

Another option, in my opinion better designed, is to use the Anti pattern Singleton , which is to share a single instance through an entire application.

public enum StorE {
  INSTANCE;
  private final List<Tipo> items = new ArrayList<>();

  public void addItem(Tipo item) {
      items.add(item);
  }

  public List<Tipo> getItems() {
      return items;
  }

  public Store getInstance() {
      return INSTANCE;
  }

}

Then, you would only do this to get the Store instance:

Store store = Store.getInstance();
store.addItem(<<algo>>);
...
    
answered by 13.09.2016 в 16:15
0

To avoid the antontron singleton and to avoid defining the list as static final , what you can do is design your application so that a class, let's call it FuenteDatos , contains your list and all the classes that need to access this list must receive an instance of FuenteDatos as argument in the constructor to work. This is called composition ratio: the dependency between the classes and FuenteDatos is a strong dependence, without an instance of that kind the others can not work.

The design would be similar to this:

public class FuenteDatos {
    private List<Dato> listaDatos = new ArrayList<>();

    public boolean agregar(Dato dato) {
        return listaDatos.add(dato);
    }

    //por poner un ejemplo
    public Dato buscar(int id) {
        Optional<Dato> dato = listaDatos.stream().filter(d -> d.id == id).findFirst();
        return dato.isPresent() ? dato.get() : null;
    }

    public void paraTodos(Consumer<Dato> funcionParaTodos) {
        listaDatos.forEach(funcionParaTodos);
    }
}

And then in the classes that need it:

//de acuerdo a tu descripción del problema
public class Almacen {
    private FuenteDatos fuenteDatos;
    public Almacen(FuenteDatos fuenteDatos) {
        this.fuenteDatos = fuenteDatos;
    }

    public void operacionX(Dato dato) {
        if (<reglas para validar dato) {
            fuenteDatos.agregar(dato);
        }
    }

    public void mostrarDatosEnConsola() {
        fuenteDatos.paraTodos(d -> System.out.println(
            String.format("Dato. Id: %d, Nombre: %s", d.getId(), d.getNombre())
            ));
    }
}

And from your main class orchestras the integration of all these components:

public class Principal {
    public static void main(String[] args) {
        //aquí creamos la instancia de FuenteDatos
        FuenteDatos fuenteDatos = new FuenteDatos();
        //aquí creamos la instancia de Almacen
        //y la asociamos a FuenteDatos
        Almacen almacen = new Almacen(fuenteDatos);
        //puedes iniciar más clases necesarias para que funcione tu aplicación aquí
        //...
        //y que comience tu aplicación
        System.out.println("Bienvenido al Almacén.");
        //resto del código...
    }
}
    
answered by 13.09.2016 в 17:30