How to display items from an ArrayList by a vector?

0

I loaded a code here, it looks like this:

class Main {
    Lista lista = new Lista();
    public static void main(String[] args) {
        i = 0;
        String[] vetorExibir;
        lista.exibicao(vetorExibir = new String[lista.lista.size()]);
        while (i < vetorExibir.length) {
            System.out.println(vetorExibir[i];
            i++;
        }
    }
}
class Lista {
    ArrayList<String> lista;
    public Lista() {
        lista = new ArrayList<>();
    }
    public String[] exibicao(String[] vetorExibir) {
        int i = 0;
        vetorExibir = new String[lista.size()];
        while (i < lista.size()) {
            vetorExibir[i] = lista.get(i);
        } return vetorExibir;
    }
}

Whereas the ArrayList already has data. It does not work, it does not display anything.

    
asked by anonymous 12.04.2014 / 21:45

1 answer

2

Several problems with your code, starting with the statement:

 lista.exibicao(vetorExibir = new String[lista.lista.size()]);

At this point, list.size () == 0, that is, you are creating an array of size zero.

The other problem is that in the display () method, you change the value of the parameter, and this will not be reflected externally in JAVA. Pro your code to work, you need to do so:

  String[] vetorExibir = lista.exibicao(...);  

so you use the vector returned by the method.

I suggest you drop your code and use what the API already offers:

  ArrayList<String> arrayList = getArrayListPopulated();
  String[] vetorExibir = arrayList.toArray(new String[arrayList.size()]);
    
12.04.2014 / 21:55