What is the ArrayList class?
ArrayList is a mutable array implementation of the List interface, part of the Collection Framework, which is responsible for the list (or dynamic array) located in the java.utils package. This class implements all optional list operations and provides methods to control the size of the array that is used to store the list. ArrayList is based on the idea of a dynamic array. Namely, the ability to add and remove elements, while increasing or decreasing as needed.What does ArrayList store?
Only reference types, any objects, including third-party classes. Strings, output streams, other collections. Wrapper classes are used to store primitive data types.ArrayList Constructors
-
ArrayList()
Empty constructor with initial internal array capacity = 10.
ArrayList<String> list = new ArrayList<>();
It is advisable to indicate the type of stored values in angle brackets. In the example above -
String
. -
ArrayList(Collection <? extends E> c)
The constructor accepts another collection, creating a new array with the elements of the passed collection:
ArrayList<String> list2 = new ArrayList<>(list);
The order of elements in the new list will be the same as the original.
-
ArrayList(int initialCapacity)
The constructor parameter is the value of the initial size of the internal array.
ArrayList<String> list2 = new ArrayList<>(10000);
If the underlying ArrayList runs out of space when new elements are added, a new larger array is created and the data is copied into it. If you know in advance when writing your code that a large number of elements will be processed in the array, you should specify a larger value for optimization purposes.
ArrayList Methods
-
add(E e)
Adds a new element to the end of the list. Returns
boolean
-value ( true - success, false - not added):ArrayList<String> list = new ArrayList<>(); list.add("Hello");
-
add(int index, E element)
Adds an element
element
at position index. When adding, all elements to the right of the specified index are shifted 1 position to the right:list.add(0, "Amigo");
Very useful when you need to insert an element anywhere in a list, but for frequent insertion operations at the beginning and middle of the ArrayList may not be a very good choice - you should look into LinkedList.
-
addAll(Collection <? extends E> collection)
Adds all the elements of collection to a list in the order they appear in collection.
-
addAll(int index, Collection <? extends E> collection)
Adding all elements
collection
to the list starting from indexindex
. In this case, all elements will shift to the right by the number of elements in the listcollection
:ArrayList<String> secondList = new ArrayList<>(); secondList.addAll(list); System.out.println("First addition: " + secondList); secondList.addAll(1, list); System.out.println("Second addition in the middle: " + secondList);
Conclusion:
Первое добавление: [Amigo, Hello] Второе добавление в середину: [Amigo, Amigo, Hello, Hello]
The methods
addAll()
also return the boolean result of adding elements. -
clear()
Removing all elements from the list.
- clone()
Returns a copy object of the array:
ArrayList<String> copyOfSecondList = (ArrayList<String>) secondList.clone(); secondList.clear(); System.out.println(copyOfSecondList);
Conclusion:
[Amigo, Amigo, Hello, Hello]
Please note that the method
clone()
returnsObject
, so after calling it you will need to cast to the required class.Cloning creates a new independent object. The example shows how purifying a cloned object did not affect the composition of its clone.
-
contains(Object o)
Checking for the presence of an object in the list, returns
boolean
a -value.System.out.println(copyOfSecondList.contains("Hello")); System.out.println(copyOfSecondList.contains("Check"));
Conclusion:
true false
-
ensureCapacity(int minCapacity)
Увеличивает размер внутреннего массива, чтобы в него поместилось количество элементов, переданных в
minCapacity
. Если массив достаточно вместителен, ниHowие преобразования не производятся.Этот метод полезен, когда возникает потребность вместить большое количество элементов в несколько итераций. Например, при создании списка емкость его внутреннего массива — 10. При загрузке данных по сети они обрабатываются асинхронно порциями и результаты помещаются в массив. Если ожидается доставка 10 000 элементов, может быть неэффективно просто добавлять эти данные каждый раз: достаточно будет в начале обработки вызвать метод
ensureCapaciry(10000)
и записывать туда данные по мере необходимости. -
forEach(Consumer<? super E> action)
Обработать в цикле ArrayList можно стандартными способами, цикл for:
// First way for(int i = 0; i< secondList.size(); i++) { System.out.println(secondList.get(i)); } И цикл for-each: // Second way for(String s : secondList) { System.out.println(s); }
В классе ArrayList есть метод для обработки каждого element, который называется также, forEach. В качестве аргумента передается реализация интерфейса Consumer, в котором нужно переопределить метод accept():
secondList.forEach(new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } });
Вывод:
Amigo Amigo Hello Hello
Метод accept принимает в качестве аргумента очередной элемент того типа, который хранит в себе ArrayList. Пример для Integer:
ArrayList<Integer> integerList = new ArrayList<>(); integerList.forEach(new Consumer<Integer>() { @Override public void accept(Integer integer) { System.out.println(integer); } });
Метод
action()
будет выполнен для каждого element. -
get(int index)
returns элемент, который расположен в указанной позиции списка.
Если
index < 0
orindex >=
максимального количества элементов списка, будет выброшено исключениеIndexOutOfBoundsException
.Это основной метод получения element из списка, время извлечения element по индексу всегда будет одинаковым, независимо от размера ArrayList.
-
indexOf(Object o)
Метод возвращает индекс первого вхождения element в списке. Если element не существует в списке, метод вернет -1.
-
isEmpty()
Метод возвращает true, если список пустой, false в обратном случае.
Если в списке содержатся только элементы
null
, метод вернет false. Иными словами,null
элементы также учитываются этим методом. -
iterator()
returns итератор для списка для последующего использования в цикле or при любой другой обработке.
Итератор для ArrayList — fail-fast. Это значит, что если коллекция изменится во время итерации, будет выброшено исключение ConcurrentModificationException. Подробнее об fail-fast и его противоположности fail-safe можно почитать здесь.
-
lastIndexOf(Object o)
Функционал метода похож на
indexOf()
, отличие в том, что возвращается индекс последнего element в списке.Если элемент не найден, также возвращает -1.
-
remove(int index)
Удаление element в указанной позиции индекса. После удаления сдвигает все элементы влево для заполнения освободившегося пространства.
Если
index<0
or>=
количество элементов списка, будет выброшено исключениеIndexOutOfBoundsException
. В результате метод возвращает элемент, который был удален. -
remove(Object o)
The method removes the passed element from the list
o
. If an element is present in the list, it is removed and all elements are shifted to the left. If the element exists in the list and is successfully removed, the method returns true; otherwise, false . -
removeAll(Collection<?> c)
If you need to remove several elements, you should not do it in a conditional loop: it is much more convenient and safer to use the method
removeAll()
. It accepts a collection of elements that will be removed from the list.The collection must contain elements of the same type that the target list stores. Otherwise it will be thrown away
ClassCastException
. The method will return true if the list has been modified as a result of the method call. -
set(int index, E element)
Replaces the element at the specified position
index
with the passed oneelement
. The index must also be greater than zero and less than the index of the last element, otherwise an exception will be thrownIndexOutOfBoundsException
. -
size()
The best way (almost the only one) to find out the size of an array.
-
sort(Comparator<? super E> c)
Sorting the list according to a given rule. A sort rule is an implemented interface
Comparator
with an overridden methodcompareTo()
.Overriding is necessary if the collection contains objects of its own class. When working with standard classes (
Integer
,String
and so on), overridingcompareTo()
is only required for non-standard sorting. -
toArray()
Converts a list to a fixed array. Note that the method returns an array of objects (
Example:Object[]
). If you need to convert a list into an array of objects of a certain type, you can pass an array into which the elements of the lists will be moved as a parameter to the method.String[] array = new String[secondList.size()]; secondList.toArray(array); for(int i = 0; i< array.length; i++) { System.out.println(array[i]); }
Conclusion:
Amigo Amigo Hello Hello
Below are the main methods of ArrayList.
Links for further reading
- A detailed article about dynamic arrays , or more precisely about
ArrayList
andLinkedList
, which perform their role in the Java language. - An article about removing elements from an ArrayList .
- Lecture on working with ArrayList in diagrams and pictures .
GO TO FULL VERSION