How to display items from an Arraylist by an array?

Asked

Viewed 560 times

0

I came up with a code here, it’s 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 Arraylist already has data.
It doesn’t work, it doesn’t display anything.

1 answer

2


several problems in your code, starting with the statement:

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

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

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. For 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 discard your code and use what the API already offers:

  ArrayList<String> arrayList = getArrayListPopulated();
  String[] vetorExibir = arrayList.toArray(new String[arrayList.size()]);
  • But why lista.size() would be 0? If there are items in Arraylist, it is larger than zero, right? Anyway, I will use your suggestion. She would be in the main method?

  • you haven’t populated the Arraylist 'list' anywhere, so that’s zero at that point.

Browser other questions tagged

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