Java 删除ArrayList中的所有元素
前提是。Java中的ArrayList
给定一个ArrayList,任务是在Java中删除ArrayList的所有元素。
例子
输入: ArrayList = [1, 2, 3, 4]
输出: ArrayList = []
输入: ArrayList = [12, 23, 34, 45, 57, 67, 89]
输出: ArrayList = []
- 使用 clear() 方法:
语法:
collection_name.clear();
** clear()方法的代码:**
public void clear() {
for (int i = 0; i < size; i++)
list[i] = null;
size = 0;
}
以下是上述步骤的实现。
// 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());
}
}
输出:
ArrayList: [Geeks, for, Geeks, Gaurav]
Size of ArrayList = 4
After clear
ArrayList: []
Size of ArrayList = 0
时间复杂度O(N)
使用removeAll()方法
语法:
collection_name.removeAll(collection_name);
** 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;
}
以下是上述步骤的实现。
// 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());
}
}
输出:
ArrayList: [Geeks, for, Geeks, Gaurav]
Size of ArrayList = 4
After clear
ArrayList: []
Size of ArrayList = 0
时间复杂度O(N^2)