java empty array list vs null elements

https:‮//‬www.lautturi.com
java empty array list vs null elements

In Java, an ArrayList is a dynamic array that can store elements of any type. It provides methods for adding, deleting, and accessing elements in the list.

There are two main ways to "empty" an ArrayList in Java: by removing all of the elements from the list, or by setting the elements to null.

To remove all of the elements from an ArrayList, you can use the clear() method of the ArrayList class. This method removes all of the elements from the list and leaves it empty.

Here's an example of how to use the clear() method to empty an ArrayList:

import java.util.ArrayList;
import java.util.List;

public class ArrayListClearer {
    public static void main(String[] args) {
        // Create a new ArrayList and add some elements to it
        List<String> list = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Clear the ArrayList
        list.clear();

        // Check the size of the ArrayList
        int size = list.size();  // size is now 0
    }
}

In this example, the clear() method is used to remove all of the elements from the ArrayList. The size() method is then used to check the size of the ArrayList, which should be 0.

To set the elements of an ArrayList to null, you can iterate over the list and set each element to null individually.

Here's an example of how to set the elements of an ArrayList to null:

import java.util.ArrayList;
import java.util.List;

public class ArrayListNuller {
    public static void main(String[] args) {
        // Create a new ArrayList and add some elements to it
        List<String> list = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Set the elements of the ArrayList to null
        for (int i = 0; i < list.size(); i++) {
            list.set(i, null);
        }
    }
}
Created Time:2017-11-03 15:57:12  Author:lautturi