Remove all items from ArrayList in Java

This code deletes all objects from the ArrayList in java. To flush ArrayList, you need to use the method of the ArrayList  clear():

import java.util.ArrayList; 
public class Clear{
public static void main(String[] args) {
// Create an ArrayList
ArrayList arraylist = new ArrayList();

//add the elements to ArrayList
arraylist.add("E1");
arraylist.add("E2");
arraylist.add("E3");
arraylist.add("E4");

// show list before deletion
System.out.println("Before: "+ arraylist);

arraylist.clear();

// show list after deletion
System.out.println("After: "+ arraylist);
}
}
Output:

Before: [e2, e1, e4, e3]
after: []

Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel !

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

N'hésitez pas si vous avez des questions.