Create objects from the elements of an array with the name that they already have JAVA

0

I have an array and I need to create an object of Element type for each element of the array. I am in the loop with the problem that you can not give an object a variable as a name so I do not know how to create them since the variable Element would be crushed all the time. Is there any way in java to do this?

I have an array called states and each state has an attribute name. The loop would be the following:

for(int i=0; i<eventos.length; i++) {
    Element start = new Element(eventos[i].getNombre(), "20em", "6em");
    start.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM));
    start.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
}
    
asked by rosariop 16.08.2018 в 10:58
source

2 answers

1

Having a ArrayList<String> with the names of the variables as you indicated, we would make a foreach loop with the array:

for(String nombre : nombreDelArray){
   Element elemento = new Element(nombre, "20em", "6em");
   //Hacer con el elemento lo que quieras hacer
}

What we do is create a Element element for each of the list, I recommend foreach to go through the lists since it is more comfortable.

    
answered by 16.08.2018 в 11:08
0

Assuming that the initial list contains objects of the class Evento (you do not indicate the specific class):

private List<Element> crearElementos(List<Evento> eventos){
    return eventos
        .stream()
        .map(this::nuevoElemento)  //Conversión a Element
        .collect(Collectors.toList());  //Agrupar en una lista
}

private Element nuevoElemento(Evento evento){
    Element start = new Element(evento.getNombre(), "20em", "6em");
    start.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM));
    start.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
    return start;
}

Basically, the streams API is used to convert each element of the class Evento to another class Element , and it is returned in a list.

    
answered by 16.08.2018 в 12:09