What are the different methods to clear a list in Java?

In Java, there are several methods you can use to clear a List.

1. The simplest and recommended method is using the `clear()` method. It clears all elements in the List and sets its length to 0. Example:

List<String> list = new ArrayList<>();

// 添加一些元素到列表中

list.add("元素1");

list.add("元素2");

// 清空列表

list.clear();

System.out.println(list); // 输出: []

2. Instantiate a new List object: By creating a new List object, you can achieve the same effect as clearing it. Example:

List<String> list = new ArrayList<>();

// 添加一些元素到列表中

list.add("元素1");

list.add("元素2");

// 清空列表

list = new ArrayList<>();

System.out.println(list); // 输出: []

It’s important to note that with this method, once the list is cleared, the original List object will no longer be accessible and will be garbage collected when there are no other references pointing to it.

3. By using the `removeAll()` method: If you only want to remove specific elements instead of the entire list, you can use the `removeAll()` method. Pass the existing list as a parameter to the `removeAll()` method, and pass in an empty list as a parameter to remove all elements. Example:

List<String> list = new ArrayList<>();

// 添加一些元素到列表中

list.add("元素1");

list.add("元素2");

// 清空列表

list.removeAll(Arrays.asList());

System.out.println(list); // 输出: []

Please choose the appropriate method to clear the List based on your needs. The `clear()` method is the most commonly used and recommended way.

bannerAds