Requisito previo: ArrayList en Java
Dada una ArrayList, la tarea es eliminar todos los elementos de la ArrayList en Java.
Ejemplos:
Input: ArrayList = [1, 2, 3, 4] Output: ArrayList = [] Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: ArrayList = []
- Usando el método clear():
Sintaxis:
collection_name.clear();
Código del método clear():
public void clear() { for (int i = 0; i < size; i++) list[i] = null; size = 0; }
A continuación se muestra la implementación del enfoque anterior:
// Java Program for remove all elements ArrayList
// Using clear() method
// import ArrayList package
import
java.util.ArrayList;
public
class
GFG {
// main method
public
static
void
main(String[] args)
{
// create empty ArrayList
ArrayList<String> list =
new
ArrayList<>();
// Adding elements of list
list.add(
"Geeks"
);
list.add(
"for"
);
list.add(
"Geeks"
);
list.add(
"Gaurav"
);
// printing initial value ArrayList
System.out.println(
"ArrayList: "
+ list);
// print size of ArrayList
System.out.println(
"Size of ArrayList = "
+ list.size());
// remove all elements using clear() method
list.clear();
// printing ArrayList
System.out.println(
"\nAfter clear\n\n"
+
"ArrayList: "
+ list);
// print size of ArrayList after clear list
System.out.println(
"Size of ArrayList = "
+ list.size());
}
}
Producción:ArrayList: [Geeks, for, Geeks, Gaurav] Size of ArrayList = 4 After clear ArrayList: [] Size of ArrayList = 0
Complejidad de tiempo: O(N)
- Usando el método removeAll()
Sintaxis:
collection_name.removeAll(collection_name);
Código del método removeAll():
public boolean removeAll(Collection list) { boolean isModi = false; Iterator ite= iterator(); while (ite.hasNext()) { if (list.contains(ite.next())) { ite.remove(); isModi = true; } } return isModi; }
A continuación se muestra la implementación del enfoque anterior:
// Java Program for remove all elements ArrayList
// Using removeAll() method
// import ArrayList package
import
java.util.ArrayList;
public
class
GFG {
// main method
public
static
void
main(String[] args)
{
// create empty ArrayList
ArrayList<String> list =
new
ArrayList<>();
// Adding elements of list
list.add(
"Geeks"
);
list.add(
"for"
);
list.add(
"Geeks"
);
list.add(
"Gaurav"
);
// printing initial value ArrayList
System.out.println(
"ArrayList: "
+ list);
// print size of ArrayList
System.out.println(
"Size of ArrayList = "
+ list.size());
// remove all elements using clear() method
list.removeAll(list);
// printing ArrayList
System.out.println(
"\nAfter clear\n\n"
+
"ArrayList: "
+ list);
// print size of ArrayList after clear list
System.out.println(
"Size of ArrayList = "
+ list.size());
}
}
Producción:ArrayList: [Geeks, for, Geeks, Gaurav] Size of ArrayList = 4 After clear ArrayList: [] Size of ArrayList = 0
Complejidad del tiempo: O(N^2)