Is it possible to dynamically instantiate Arraylist in java?

Asked

Viewed 450 times

1

For example, if I need to create arraylists for each person q register in my system:

ArrayList pessoa1 ArrayList();
ArrayList pessoa2 ArrayList();
ArrayList pessoa3 ArrayList();

The problem is I don’t know how many people are going to register so it would have to be created dynamically, like:

for(int i = 0; i < numeroPessoasCadastradas; i++){
    pessoa[i] = new ArrayList();
}

It’s possible to do something like that?

  • 2

    Yes, perfectly possible. Arraylist has no set size. It even has a size but expands as it is filled.

  • Hello, I tried to create this for but java gives me the following error: Exception in thread "main" java.lang.Nullpointerexception

  • 1

    So it would be interesting to better explain the problem, because it was not very clear the purpose of this.

  • Probably the Arraylist pessoa was not created.

  • Try to start pessoa before. You are using a vector of ArrayList, which is strange to me; anyway, you could, before the for, do pessoa = new ArrayList[numeroPessoasCadastradas], but it’s very strange to do this. What is the context of you needing to do this? Why the ArrayLists are not typed?

  • @Thiago, I’d like to add an addendum on Arraylist: here. I believe I can help in understanding your question. In your solution you use Arraylist.

Show 1 more comment

1 answer

1


It’s possible, only, the way you wrote, pessoa[] it’s just one Array, and Arrays do not grow dynamically as you would like:

import java.util.ArrayList;

public class MeuPequenoArray {

    public static void main(String[] args) {

        int numeroPessoasCadastradas = 12345; // tamanho fixo
        ArrayList[] pessoa = new ArrayList[numeroPessoasCadastradas];

        for (int i = 0; i < numeroPessoasCadastradas; i++) {
            pessoa[i] = new ArrayList();
        }
    }
}

A possible solution is to create a List of ArrayLists - or a ArrayList of ArrayLists:

import java.util.ArrayList;

public class MeuEnormeArrayList {

    public static void main(String[] args) {

        int numeroPessoasCadastradas = 12; // esse número não importa mais
        ArrayList<ArrayList> pessoa = new ArrayList<ArrayList>();

        for(int i = 0; i < numeroPessoasCadastradas; i++){
            pessoa.add(new ArrayList<>());
        }
    }   
}
  • would like to add an Addendum on Arraylist: here. I believe it can help in understanding your answer. In your solution you use Arraylist.

Browser other questions tagged

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