How to completely delete an Arraylist and a List

Asked

Viewed 339 times

4

I would like to know how to destroy the erase completely a ArrayList and a List in full at runtime.

example:

ArrayList<Elemento> e = new ArrayList();//Elemento e uma classe

for (int i = 0; i<10;i++)
{
   e.add(new Elemento());
   e.get(i).texto = "teste";
   e.get(i).texto2 =  "algo";
   e.get(i).numero = i;
}

How to destroy e completely or erase it?

  • 7

    ...e.clear() ?

  • Do you want to reset the elements or make them all disappear? What do you mean by destroying, or completely or erasing?

  • @moustache that all disappear , as if not created.

  • Really the .clear() solved the problem

2 answers

5


The best way to do this is to create a new instance:

ArrayList<Elemento> e = new ArrayList(); //Elemento e uma classe
for (int i = 0; i<10;i++) {
   e.add(new Elemento());
   e.get(i).texto = "teste";
   e.get(i).texto2 =  "algo";
   e.get(i).numero = i;
}
e = new ArrayList();

The clear() can resolve this differently and each has its place.

ArrayList<Elemento> x = new ArrayList<>();
x.add(new Elemento())
ArrayList<Elemento> y = x;
x = new ArrayList<>(); //y permanece com o elemento, afinal x passou ter uma nova instância

ArrayList<Elemento> x = new ArrayList<>();
x.add(new Elemento())
ArrayList<Elemento> y = x;
x.clear(); //y não tem mais nada também

I put in the Github for future reference.

2

I believe that creating a new instance will solve your problems.

e = new ArrayList();
  • Yeah? Why is that? Your answer may be correct, but if you don’t explain the reason in more detail it will hardly help someone else (and it might even help the AP learn from the mistake). I won’t vote to recommend exclusion yet, but please edit it and improve it, okay?

Browser other questions tagged

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