Arraylist - Place index next to element

Asked

Viewed 114 times

-2

I have an application where the user informs via JSF a unit name.

When the system finds the drive, it fills a List<String> with the unit data. With this List filled in, the index of each row shall be placed next to the relevant item:

[0] - elemento da linha aqui
[1] - elemento da linha aqui 1
[2] - elemento da linha aqui 2
[3] - etc

I can print on the console, but when sending to JSF the data is overwritten.

my bean is like this:

public List<String> getUnidadesAdicionadas() {
List<String> lista = new ArrayList<String>();
    try {

            if (!findUnidadeCampanha(unidade)) {
                addMensagemErro("erro");
            }  else { 
            unidadesAdd.add(unidade.getNome());
            quantidadeUnidades = unidadesAdd.size();


            lista.addAll(unidadesAdd);

            for (int i = 1; i < unidadesAdd.size(); i++) {   
                //Para cada item percorrido   atribuir o valor na variavel indice;
                String elemento  = unidadesAdd.get(i) + "\n";
                 int  index  = i++;
                }

            unidade.setNome("");//limpar campo UNIDADE


        } 
    } catch (Exception e) {
        e.printStackTrace();
    }
    return lista;
}

and my jsf like this:

 <h:outputText value="#{proformeGerencialMBean.index}"  escape="false" />   - <h:outputText value="#{proformeGerencialMBean.elemento}"  escape="false" />

3 answers

0

Right away I could see that you are returning the same list instead of unitsAdd which is the one you are messing with the index, it would not be returning unitsAdd?

List<String> lista = new ArrayList<String>();

This list you have created will never change because you are only adding the element to it.

0

Try to change your go to:

for (int i = 1; i < lista.size(); i++) {   
    //Para cada item percorrido   atribuir o valor na variavel indice;
    String elemento  = lista.get(i) + "\n";
    int  index  = i++;
}

0

The solution would be more or less this maybe you have to create another list and add the elements in it, you have to test to see.

Integer contador = 0;

for (String elemento : lista) {   
    //Para cada item percorrido atribuir o valor na variavel indice;
    elemento = "[" + contador + "]" + elemento;
    contador++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.