Home > Java > javaTutorial > How to use the ArrayList.clear() method in Java to clear elements in a list?

How to use the ArrayList.clear() method in Java to clear elements in a list?

WBOY
Release: 2023-11-18 09:11:01
Original
1512 people have browsed it

How to use the ArrayList.clear() method in Java to clear elements in a list?

ArrayList in Java is a very commonly used data structure that allows us to dynamically store and manipulate data. In some cases, we may need to clear all elements in the list to refill or free up memory space. The ArrayList class provides a clear() method that can help us achieve this goal easily.

The clear() method is a member method of the ArrayList class, used to delete all elements in the list. This method is very simple, it does not receive any parameters and does not return any value. When we call the clear() method of the ArrayList object, it removes all elements from the list and resets the length of the list to 0.

The following is a sample code for clearing ArrayList:

import java.util.ArrayList;

public class ClearArrayListExample {
    public static void main(String[] args) {
        // 创建一个ArrayList对象并添加一些元素
        ArrayList<String> list = new ArrayList<>();
        list.add("元素1");
        list.add("元素2");
        list.add("元素3");

        System.out.println("清空前的列表内容:" + list);

        // 调用clear()方法清空列表
        list.clear();

        System.out.println("清空后的列表内容:" + list);
    }
}
Copy after login

Run the above code, the output result is as follows:

清空前的列表内容:[元素1, 元素2, 元素3]
清空后的列表内容:[]
Copy after login

As can be seen from the results, the clear() method will All elements of are removed and the list becomes an empty list.

It should be noted that the clear() method only deletes the elements in the list, but does not release the memory space occupied by the ArrayList object. The reference to the ArrayList object itself still exists, just the list is empty. If you want to completely free the memory, you can set the ArrayList object to null or recreate a new ArrayList object.

In short, we can easily clear the elements in the list by calling the clear() method of ArrayList to prepare for subsequent operations. This method is very simple and easy to use, and is a commonly used method when we deal with ArrayList.

The above is the detailed content of How to use the ArrayList.clear() method in Java to clear elements in a list?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template