Очистить весь list java

Class ArrayList

Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(. ));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Читайте также:  Python django create app

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

Clear ArrayList with clear() vs. removeAll()

Learn to clear an ArrayList or empty an ArrayList in Java. Clearing a list means removing all elements from the list. It is the same as resetting the list to its initial state when it has no element stored in it.

To clear an arraylist in java, we can use two methods.

Both methods will finally empty the list. But there is a difference in how they perform the empty operation.

The following Java program clears an arraylist using the clear() API.

ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); list.clear(); Assertions.assertEquals(0, list.size());

2. Clear ArrayList with removeAll()

Java program to remove all elements of an arraylist with removeAll() method. The removeAll() method removes all the elements in the current list that are present in the specified collection.

In this example, we are passing the self-reference of the list to the removeAll() method.

ArrayList list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); list.removeAll(list); Assertions.assertEquals(0, list.size());

3. Difference between clear() and removeAll()

As I said before, both methods empty a list. But the difference lies in how they make the list clear. Let’s see the code for both methods to understand the actions they perform.

The clear() method is simple. It iterates over the list and assigns null to each index in the list.

In removeAll() method, it first checks if the element is present or not using contains() method. If the element is present then it is removed from the list. This happens for all the elements in the loop.

public boolean removeAll(Collection c) < Objects.requireNonNull(c); return batchRemove(c, false); >private boolean batchRemove(Collection c, boolean complement) < final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try < for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; >finally < // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) < System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; >if (w != size) < // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; >> return modified; >

By going through the sourcecode of both methods, we can safely say that clear() method gives much better performance because of less number of statements it executes.

The removeAll() method lack in performance because of extra calls to contains() method. But, still removeAll() method is useful in cases such as merge two arraylists without duplicate elements.

Источник

ArrayList clear() Method – How to Empty or clear ArrayList in Java

1. ArrayList clear() method Syntax

Before we look in to more details, let’s look at the clear() method syntax from the ArrayList.The ArrayList clear() method will iterate through each element of the list and just sets the array elements to null .

If we just want to clear the ArrayList, clear() method will much faster as it only set the reference to each element as null doing no additional data manipulation.

How to empty and ArrayList in Java?

We can use ArrayList.clear() or ArrayList.removeAll() method to empty an ArrayList. The clear() method is the fastest as it only set the reference to the underlying array as null while the removeAll() will perform some additional work.

1. ArrayList clear() method Example

Here is a complete example to clear all the elements from an ArrayList.

package com.javadevjournal; import java.util.ArrayList; import java.util.List; public class ArraylistClearExample < public static void main(String[] args) < List < String >list = new ArrayList < >(); list.add("Sunday"); list.add("Monday"); list.add("Tuesday"); list.add("Wednesday"); list.add("Thursday"); list.add("Friday"); list.add("Saturday"); System.out.println(list); //clear the list list.clear(); System.out.println(list); > >
[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] []

When performing ArrayList.clear() it only removes references to array elements and sets size to 0 , however, capacity stays as it was.

2. ArrayList.clear() or Create a New List?

When working on the ArrayList clear() method, there is a natural question “Should we use clear() method or create a new list using new ArrayList() ?”. There are multiple reason we should prefer to use clear() method over new list.

  • Most times we might not be allowed to reassign a reference field that points to an ArrayList.
  • The variable might be declared as List. The actual type could be LinkedList and you want to preserve it instead of replacing the implementation with an ArrayList.
class App < // Can clear() but not reassign final List < String >list = new ArrayList < >(); >

Keep in mind that it might be faster if the ArrayList will be cleared and refilled thousand times repeatedly as the clear() method will only clear the elements from the list but won’t change the size of backing array, this can definitely help us avoid dynamic resizing of the ArrayList.

3. ArrayList.clean() vs ArrayList.removeAll()

Both ArrayList.clear() and ArrayList.removeAll() empty an ArrayList, however they clear the list differently. Let’s look at the difference between the ArrayList.clear() vs ArrayList.removeAll().

  • The clear() method clear the list by assigning the null value to each element. It does not change the underlying backing Array.
  • In removeAll() method, it first check if the element is present using the contains() method, it removes the element in case the item is present. The removeAll() perform some additional steps before removing an element from the underlying list.
public boolean removeAll(Collection c) < Objects.requireNonNull(c); boolean modified = false; Iterator it = iterator(); while (it.hasNext()) < if (c.contains(it.next())) < it.remove(); modified = true; >> return modified; >
From ArrayList
public boolean removeAll(Collection c) < return batchRemove(c, false, 0, size); >boolean batchRemove(Collection c, boolean complement, final int from, final int end) < Objects.requireNonNull(c); final Object[] es = elementData; int r; // Optimize for initial run of survivors for (r = from;; r++) < if (r == end) return false; if (c.contains(es[r]) != complement) break; >int w = r++; try < for (Object e; r < end; r++) if (c.contains(e = es[r]) == complement) es[w++] = e; >catch (Throwable ex) < // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. System.arraycopy(es, r, es, w, end - r); w += end - r; throw ex; >finally < modCount += end - w; shiftTailOverGap(es, w, end); >return true; >

Let’s look at some of the extra points while using these options:

  1. The clear() method on avg is much faster since it doesn’t have to deal with all those extra method calls as used in the removeAll() method.
  2. The c.contains() increase the time complexity of removeAll() method. ( O(n) vs O(n2) )

Summary

In this article, we look at the ArrayList clear() method. We saw when we should use the clear() method as compare to creating and assigning a new ArrayList. At the end of this article, we look at the difference between the ArrayList clear() vs removeAll() method. The source code for these articles is available on our GitHub repository.

Источник

Java ArrayList.clear () Метод

Метод clear () используется для удаления всех элементов из списка. Список будет пустым после возврата этого вызова.

Пакет: java.util

Платформа Java: Java SE 8

Возвращаемое значение:
Этот метод не возвращает никакого значения.

Наглядное представление метода ArrayList.clear ()

Пример: метод ArrayList.clear ()

В следующем примере создается ArrayList емкостью 7 элементов. После добавления некоторых элементов мы удалили все содержимое, используя метод clear (0.

import java.util.*; public class test < public static void main(String[] args) < // create an empty array list with an initial capacity ArrayListcolor_list = new ArrayList(7); // use add() method to add values in the list color_list.add("White"); color_list.add("Black"); color_list.add("Red"); color_list.add("White"); color_list.add("Yellow"); color_list.add("Red"); color_list.add("White"); // Print out the colors in the ArrayList System.out.println("****Color list****"); for (int i = 0; i < 7; i++) < System.out.println(color_list.get(i).toString()); >// Remove all the elements using clear() color_list.clear(); //Now size of the list System.out.println("After using clear() method, the size of the list is: " + color_list.size()); > > 
F: java> javac test.java F: java> тест java **** Цветовой список **** белый черный красный белый желтый красный белый После использования метода clear () размер списка составляет: 0

Редактор кода Java:

Источник

Java ArrayList.clear () Метод

Метод clear () используется для удаления всех элементов из списка. Список будет пустым после возврата этого вызова.

Пакет: java.util

Платформа Java: Java SE 8

Возвращаемое значение:
Этот метод не возвращает никакого значения.

Наглядное представление метода ArrayList.clear ()

Пример: метод ArrayList.clear ()

В следующем примере создается ArrayList емкостью 7 элементов. После добавления некоторых элементов мы удалили все содержимое, используя метод clear (0.

import java.util.*; public class test < public static void main(String[] args) < // create an empty array list with an initial capacity ArrayListcolor_list = new ArrayList(7); // use add() method to add values in the list color_list.add("White"); color_list.add("Black"); color_list.add("Red"); color_list.add("White"); color_list.add("Yellow"); color_list.add("Red"); color_list.add("White"); // Print out the colors in the ArrayList System.out.println("****Color list****"); for (int i = 0; i < 7; i++) < System.out.println(color_list.get(i).toString()); >// Remove all the elements using clear() color_list.clear(); //Now size of the list System.out.println("After using clear() method, the size of the list is: " + color_list.size()); > > 
F: java> javac test.java F: java> тест java **** Цветовой список **** белый черный красный белый желтый красный белый После использования метода clear () размер списка составляет: 0

Редактор кода Java:

Источник

Оцените статью