I am starting to work with List in Java, my problem is the following, I am trying to fill a list of objects, the classes are the following: Class Changes:
public class Cambios {
private List<Cambio> cambios;
public List<Cambio> getCambios() {
return cambios;
}
public void setCambios(List<Cambio> cambios) {
this.cambios = cambios;
}
}
Change Class:
public class Cambio {
String idCard;
String idList;
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getIdList() {
return idList;
}
public void setIdList(String idList) {
this.idList = idList;
}
}
I am trying to fill them in the following way through the sets, but I do not know very well how the lists work, thanks in advance
Cambios cambios;
Cambio cambio;
List <Cambio> cambioLista = null;
for (int i=0; i<10; i++){
String idCard= "Valor de id" + i);
cambioLista.get(i).setIdCard(idCard);
cambios.setCambios(cambioLista);
}
What you are using is an interface, you can use it as a reference variable or implement it directly in the class and override its methods but you can never have an instance of any object of that type.
I recommend you use the ArrayList class , it will allow you to create a list of objects of the type defined within the ArrayList modifier
<E>
. Here is your modified code.First class
Second class
There are ways to optimize the code so as not to be redundant, but for reasons of understanding so as not to be drastic with the modifications I did it this way, I recommend you study about the extended for and review the API of the ArrayList class to learn more about its methods.
To create a list of objects you need to first initialize the list. In your case the list is a property of the class
Cambios
, so you need to create an object of that class, instantiate it and then initialize the list:To fill the list we call the method
add
and pass it an object of the type of which the list is declared. In your case the list will contain objects of the classCambio
, so we need to first create objects of that class and then add them to the list: