Progress28.ru

IT Новости
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

List arraylist java

Списочный массив ArrayList

В Java массивы имеют фиксированную длину и не могут быть увеличены или уменьшены. Класс ArrayList реализует интерфейс List и может менять свой размер во время исполнения программы, при этом не обязательно указывать размерность при создании объекта. Элементы ArrayList могут быть абсолютно любых типов в том числе и null.

Пример создания объекта ArrayList

Можно инициализировать массив на этапе определения. Созданный объект list содержит свойство size. Обращение к элементам массива осуществляется с помощью метода get(). Пример :

Добавление элемента в массив ArrayList, метод add

Работать с ArrayList просто: необходимо создать объект и вставлять созданные объекты методом add(). Обращение к элементам массива осуществляется с помощью метода get(). Пример:

Замена элемента массива ArrayList, метод set

Чтобы заменить элемент в массиве, нужно использовать метод set() с указанием индекса и новым значением.

Удаление элемента массива ArrayList, метод remove

Для удаления элемента из массива используется метод remove(). Можно удалять по индексу или по объекту:

ПРИМЕЧАНИЕ: элементы, следующие после удалённого элемента, перемещаются на одну позицию ближе к началу. То же самое относится и к операции вставки элемента в середину списка.

Для очистки всего массива используется метод clear():

Определение позиции элемента ArrayList, метод indexOf

В списочном массиве ArrayList существует метод indexOf(), который ищет нужный элемент и возвращает его индекс.

Отсчёт в массиве начинается с 0, если индекс равен 2, значит он является третьим в массиве.

Проверка наличие элемента в ArrayList, метод contains

Чтобы узнать, есть в массиве какой-либо элемент, можно воспользоваться методом contains(), который вернёт логическое значение true или false в зависимости от присутствия элемента в наборе :

Понятно, что в массиве никаких овощей быть не может, поэтому в консоле будет отображено false.

Создание массива из элементов ArrayList, метод toArray

Для конвертирования набора элементов в обычный массив необходимо использовать метод toArray().

Интерфейс List

java.util.List является интерфейсом и его следует использовать вместо ArrayList следующим образом :

Или укороченный вариант для Java 7:

В примере тип ArrayList заменен на List, но в объявлении оставлен new ArrayList(). Всё остальное остаётся без изменений. Это является рекомендуемым способом.

Интерфейс List реализует более общий интерфейс коллекции Collection.

Преобразование массива в список, Arrays

Для создания массива можно не только добавлять по одному объекту через метод add(), но и сразу массив с использованием Arrays.asList(. ).

Пример создания и инициализации массива из объектов Integer.

У данного способа есть недостаток. Если вы определили списочный массив таким образом, то уже не можете вставлять или удалять элемент, хотя при этом можете изменять существующий элемент.

Java ArrayList tutorial

Java ArrayList tutorial shows how to work with ArrayList collection in Java. Located in the java.util package, ArrayList is an important collection of the Java collections framework.

is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A is an object that represents a group of objects.

Java ArrayList

ArrayList is an ordered sequence of elements. It is dynamic and resizable. It provides random access to its elements. Random access means that we can grab any element at constant time. An ArrayList automatically expands as data is added. Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null .

Elements in the ArrayList are accessed via an integer index. Indexes are zero-based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time.

An ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList , its capacity grows automatically. Choosing a proper capacity can save some time.

Java ArrayList adding single items

Single elements can be added to an ArrayList with the add() method.

The example adds elements to an array list one by one.

An ArrayList is created. The data type specified inside the diamond brackets ( ) restricts the elements to this data type; in our case, we have a list of strings.

An element is appended at the end of the list with the add() method.

This time the overloaded add() method inserts the element at the specified position; The «C#» string will be located at the second position of the list; remember, the ArrayList is an ordered sequence of elements.

With the for loop, we go through the ArrayList list and print its elements.

This is the output. Note that the elements keep the order they were inserted.

Java List.of

Since Java 9, we have a couple of factory methods for creating lists having a handful of elements. The created list is immutable.

In the example, we create two lists that have four and three elements.

Java ArrayList get() and size()

The get() returns the element at the specified position in this list and the size() returns the size of the list.

The example uses the get() and size() methods of the ArrayList

The get() method returns the second element, which is «orange».

The size() method determines the size of our colours list; we have four elements.

This is the output of the example.

Java ArrayList copy

A copy of a list can be generated with List.copy() method.

The example creates a copy of a list with List.copy() .

Raw ArrayList

An ArrayList can contain various data types. These are called raw lists.

Raw lists often require casts and they are not type safe.

The example adds five different data types into an array list — a string, double, integer, object, and enumeration.

When we add multiple data types to a list, we omit the angle brackets.

This is the output.

Java ArrayList add multiple elements

The following example uses the addAll() method to add multiple elements to a list in one step.

Two lists are created. Later, the elements of the lists are added to the third list with the addAll() method.

The addAll() method adds all of the elements to the end of the list.

Читать еще:  Ошибка подключения высокоскоростное подключение

This overloaded method adds all of the elements starting at the specified position.

This is the output of the example.

Java ArrayList modifying elements

The next example uses methods to modify the ArrayList .

An ArrayList is created and modified with the set() , add() , remove() , and clear() methods.

The set() method replaces the fourth element with the «watch» item.

The add() method adds a new element at the end of the list.

The remove() method removes the first element, having index 0.

The overloaded remove() method remove the first occurrence of the «pen» item.

The clear() method removes all elements from the list.

The isEmpty() method determines if the list is empty.

This is the output of the example.

Java ArrayList removeIf

The removeIf() method removes all of the elements of a collection that satisfy the given predicate.

In our example, we have an ArrayList of integers. We use the removeIf method to delete all negative values.

All negative numbers are removed from the array list.

This is the output.

Java ArrayList removeAll

The removeAll() method removes from this list all of its elements that are contained in the specified collection. Note that all elements are removed with clear() .

In the example, we remove all «a» letters from the list.

Java ArrayList replaceAll

The replaceAll() method replaces each element of a list with the result of applying the operator to that element.

The example applies an operator on each of the list elements; the elements’ letters are transformed to uppercase.

A UnaryOperator that transforms letters to uppercase is created.

The operator is applied on the list elements with the replaceAll() method.

This is the output.

The second example uses the replaceAll() method to capitalize string items.

We have a list of string items. These items are capitalized with the help of the replaceAll() method.

A custom UnaryOperator is created.

Inside the UnaryOperator’s apply() method, we retur the string with its first letter in uppercase.

The operator is applied on the list items.

This is the output of the example.

Java ArrayList contains()

The contains() method returns true if a list contains the specified element.

The example checks if the specified item is in the list.

The message is printed if the item is in the list.

This is the output.

Getting index of elements in ArrayList

Each of the elements in an ArrayList has its own index number. The indexOf() returns the index of the first occurrence of the specified element, or -1 if the list does not contain the element. The lasindexOf() returns the index of the last occurrence of the specified element, or -1 if the list does not contain the element.

The example prints the first and last index of the «orange» element.

This is the example output.

Java list of lists

The example creates three lists of integers. Later, the lists are added into another fourth list.

A list of integers is created.

A list of lists is created.

We use two for loops to go through all the elements.

This is the output of the program.

Java ArrayList subList

The subList() method returns a view of the portion of a list between the specified fromIndex, inclusive, and toIndex, exclusive. The changes in a sublist are reflected in the original list.

The example creates a sublist from a list of items.

A sublist is created with the subList() method; it contains items with indexes 2, 3, and 4.

We replace the first item of the sublist; the modification is reflected in the original list, too.

This is the output of the example.

Java ArrayList traversing

In the following example, we show five ways to traverse an ArrayList .

In the example, we traverse an array list of integers with for loops, while loop, iterator, and forEach() construct.

We have created an ArrayList of integers.

Here, we use the classic for loop to iterate over the list.

The second way uses the enhanced-for loop, which was introduced int Java 5.

The third way uses the while loop.

Here, a ListIterator is used to traverse the list.

In the last way, we use the forEach() method, which was introduced in Java 8.

The example prints the elements of a list to the console, utilizing various techniques.

Java ArrayList sorting

There are different wasy to sort an ArrayList .

Sorting ArrayList with its sort method

The ArrayList’s sort() method sorts a list according to the order induced by the specified comparator.

We have an ArrayList of custom Person classes. We sort the persons according to their age in a reversed order.

This line sorts the persons by their age, from the oldest to the youngest.

This is the output.

Sorting ArrayList with Java 8 stream

In the second example, we use Java stream to sort the ArrayList . Streams API is a more powerful way to do sorting.

In this example, we have a list of countries. Each country has a name and population. The countries are sorted by population.

With the stream() method, we create a stream from a list. The sorted() method sorts elements according to the provided comparator. With Integer.compare() we compare the populations of countries. With collect() , we transform the stream into a list of countries.

This is the output. The countries are sorted by their population in ascending mode.

Working with ArrayList and simple Java array

The following example uses an ArrayList with a simple Java array.

An ArrayList is converted to an array and vice versa.

With the Arrays.asList() method, we create a fixed-size list backed by the specified array.

The ArrayList’s toArray() is used to convert a list to an array.

Stream to list

Java streams can be converted to lists using collectors.

We have a stream of strings. We convert the stream to a list with Collectors.toList() .

This is the output.

In this tutorial, we have worked with the Java ArrayList container.

Читать еще:  Java text simpledateformat

ArrayList в Java с примерами

Сегодня мы поработаем с ArrayList в Java: посмотрим на примерах самые популярные и полезные методы.

Данный урок является прямым продолжением статьи Коллекции в java, в которой мы разобрали основы и структуру классов коллекций. Теперь, попробуем немного попрактиковаться на примерах.

ArrayList — коллекция на основе массива. Это означает, что она имеет все преимущества и недостатки массивов java.

Это также означает, что работа с элементами данной коллекции подразумевает под собой работу с элементами массива. То есть — «под капотом» данного класса находится массив в чистом виде. Фактически, разработчики предоставляют нам удобные и простые методы для работы с массивом. Соответственно, использовать ArrayList нужно тогда, когда необходима скорость чтения из коллекции, но менее важна скорость удаления данных.

Какие основные методы предоставляет нам ArrayList:

  • add(element) — добавляет элемент в коллекцию;
  • get(index) — достает элемент по индексу;
  • clear() — полностью очищает коллекцию;
  • addAll(another_collection) — добавляет один список в другой;
  • remove(index) — удяляет объект по индексу;
  • remove(object) удаляет по объекту;
  • removeAll(collection_with_remove_elements) — если нужно удалить целый список объектов;
  • size() — возвращает длину коллекции;
  • isEmpty() — проверяет на пустоту;
  • forEach() — обход всех элементов.

Выше я перечислил только самые используемые методы класса ArrayList. Теперь, посмотрим пример их использования:

Как видно на примере выше — работать с ArrayList очень просто и удобно. Названия методов говорят сами за себя.

Начнем с самого начала инициализации ArrayList. Все списки принимают только объекты одного типа. Поэтому, перед инициализацией необходимо указать: с каким типом данных мы будем работать. В примере выше я выбрал тип данных String поэтому должен был явно указать его при создании коллекции массива. Далее, при работе с колекцией, я должен добавлять только строки и работать со строками. Иначе, будет ошибка компиляции. Одной из причин появления классов оберток для примитивных типов является то, что коллекции не работают с примитивами — только с объектами. Поэтому, такой тип записи работать не будет:

Если Вы планируете создавать списки целочисленных или дробних значений — нужно воспользоваться классами обертками примитивных типов:

Отдельно я хочу показать как обходить ArrayList и выводить его значения.

Поскольку работа с элементами ArrayList и особенно вывод их в консоль — очень распространенная операция, я решил показать несколько примеров вывода. Конечно же, я предпочитаю тот, который самый простой и требует найменьше затрат по написанию:

Это все, что я хотел показать по теме работы с ArrayList. Когда Вы начнете использовать данный вид коллекции — примеры выше помогут разобраться на начальных этапах. Дальше, их использование будет интуитивным и понятным.

Java ArrayList tutorial

Java ArrayList tutorial shows how to work with ArrayList collection in Java. Located in the java.util package, ArrayList is an important collection of the Java collections framework.

is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A is an object that represents a group of objects.

Java ArrayList

ArrayList is an ordered sequence of elements. It is dynamic and resizable. It provides random access to its elements. Random access means that we can grab any element at constant time. An ArrayList automatically expands as data is added. Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null .

Elements in the ArrayList are accessed via an integer index. Indexes are zero-based. Indexing of elements and insertion and deletion at the end of the ArrayList takes constant time.

An ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList , its capacity grows automatically. Choosing a proper capacity can save some time.

Java ArrayList adding single items

Single elements can be added to an ArrayList with the add() method.

The example adds elements to an array list one by one.

An ArrayList is created. The data type specified inside the diamond brackets ( ) restricts the elements to this data type; in our case, we have a list of strings.

An element is appended at the end of the list with the add() method.

This time the overloaded add() method inserts the element at the specified position; The «C#» string will be located at the second position of the list; remember, the ArrayList is an ordered sequence of elements.

With the for loop, we go through the ArrayList list and print its elements.

This is the output. Note that the elements keep the order they were inserted.

Java List.of

Since Java 9, we have a couple of factory methods for creating lists having a handful of elements. The created list is immutable.

In the example, we create two lists that have four and three elements.

Java ArrayList get() and size()

The get() returns the element at the specified position in this list and the size() returns the size of the list.

The example uses the get() and size() methods of the ArrayList

The get() method returns the second element, which is «orange».

The size() method determines the size of our colours list; we have four elements.

This is the output of the example.

Java ArrayList copy

A copy of a list can be generated with List.copy() method.

The example creates a copy of a list with List.copy() .

Raw ArrayList

An ArrayList can contain various data types. These are called raw lists.

Raw lists often require casts and they are not type safe.

The example adds five different data types into an array list — a string, double, integer, object, and enumeration.

When we add multiple data types to a list, we omit the angle brackets.

This is the output.

Java ArrayList add multiple elements

The following example uses the addAll() method to add multiple elements to a list in one step.

Two lists are created. Later, the elements of the lists are added to the third list with the addAll() method.

The addAll() method adds all of the elements to the end of the list.

Читать еще:  Java lang exceptionininitializererror фсс

This overloaded method adds all of the elements starting at the specified position.

This is the output of the example.

Java ArrayList modifying elements

The next example uses methods to modify the ArrayList .

An ArrayList is created and modified with the set() , add() , remove() , and clear() methods.

The set() method replaces the fourth element with the «watch» item.

The add() method adds a new element at the end of the list.

The remove() method removes the first element, having index 0.

The overloaded remove() method remove the first occurrence of the «pen» item.

The clear() method removes all elements from the list.

The isEmpty() method determines if the list is empty.

This is the output of the example.

Java ArrayList removeIf

The removeIf() method removes all of the elements of a collection that satisfy the given predicate.

In our example, we have an ArrayList of integers. We use the removeIf method to delete all negative values.

All negative numbers are removed from the array list.

This is the output.

Java ArrayList removeAll

The removeAll() method removes from this list all of its elements that are contained in the specified collection. Note that all elements are removed with clear() .

In the example, we remove all «a» letters from the list.

Java ArrayList replaceAll

The replaceAll() method replaces each element of a list with the result of applying the operator to that element.

The example applies an operator on each of the list elements; the elements’ letters are transformed to uppercase.

A UnaryOperator that transforms letters to uppercase is created.

The operator is applied on the list elements with the replaceAll() method.

This is the output.

The second example uses the replaceAll() method to capitalize string items.

We have a list of string items. These items are capitalized with the help of the replaceAll() method.

A custom UnaryOperator is created.

Inside the UnaryOperator’s apply() method, we retur the string with its first letter in uppercase.

The operator is applied on the list items.

This is the output of the example.

Java ArrayList contains()

The contains() method returns true if a list contains the specified element.

The example checks if the specified item is in the list.

The message is printed if the item is in the list.

This is the output.

Getting index of elements in ArrayList

Each of the elements in an ArrayList has its own index number. The indexOf() returns the index of the first occurrence of the specified element, or -1 if the list does not contain the element. The lasindexOf() returns the index of the last occurrence of the specified element, or -1 if the list does not contain the element.

The example prints the first and last index of the «orange» element.

This is the example output.

Java list of lists

The example creates three lists of integers. Later, the lists are added into another fourth list.

A list of integers is created.

A list of lists is created.

We use two for loops to go through all the elements.

This is the output of the program.

Java ArrayList subList

The subList() method returns a view of the portion of a list between the specified fromIndex, inclusive, and toIndex, exclusive. The changes in a sublist are reflected in the original list.

The example creates a sublist from a list of items.

A sublist is created with the subList() method; it contains items with indexes 2, 3, and 4.

We replace the first item of the sublist; the modification is reflected in the original list, too.

This is the output of the example.

Java ArrayList traversing

In the following example, we show five ways to traverse an ArrayList .

In the example, we traverse an array list of integers with for loops, while loop, iterator, and forEach() construct.

We have created an ArrayList of integers.

Here, we use the classic for loop to iterate over the list.

The second way uses the enhanced-for loop, which was introduced int Java 5.

The third way uses the while loop.

Here, a ListIterator is used to traverse the list.

In the last way, we use the forEach() method, which was introduced in Java 8.

The example prints the elements of a list to the console, utilizing various techniques.

Java ArrayList sorting

There are different wasy to sort an ArrayList .

Sorting ArrayList with its sort method

The ArrayList’s sort() method sorts a list according to the order induced by the specified comparator.

We have an ArrayList of custom Person classes. We sort the persons according to their age in a reversed order.

This line sorts the persons by their age, from the oldest to the youngest.

This is the output.

Sorting ArrayList with Java 8 stream

In the second example, we use Java stream to sort the ArrayList . Streams API is a more powerful way to do sorting.

In this example, we have a list of countries. Each country has a name and population. The countries are sorted by population.

With the stream() method, we create a stream from a list. The sorted() method sorts elements according to the provided comparator. With Integer.compare() we compare the populations of countries. With collect() , we transform the stream into a list of countries.

This is the output. The countries are sorted by their population in ascending mode.

Working with ArrayList and simple Java array

The following example uses an ArrayList with a simple Java array.

An ArrayList is converted to an array and vice versa.

With the Arrays.asList() method, we create a fixed-size list backed by the specified array.

The ArrayList’s toArray() is used to convert a list to an array.

Stream to list

Java streams can be converted to lists using collectors.

We have a stream of strings. We convert the stream to a list with Collectors.toList() .

This is the output.

In this tutorial, we have worked with the Java ArrayList container.

Ссылка на основную публикацию
Adblock
detector