Arraylist string remove java

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

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

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

ArrayList list = new ArrayList ();

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

ArrayList list; list = Arrays.asList(new String[] ); System.out.println ("Размер массива равен '" + Integer.valueOf (list.size()) + "' элементам");

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

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

ArrayList list; list = new ArrayList 

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

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

list.add("Яблоко"); list.add("Груша"); list.add("Слива"); list.set(1, "Персик"); System.out.println ( "2-ой элемент массива '" + list.get(1) + "'");

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

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

list.remove(0); // удаляем по индексу list.remove("Слива"); // удаляем по объекту

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

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

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

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

int index = list.indexOf("Слива"); // выводим имя элемента и его номер в массиве System.out.println (list.get(index) + " числится под номером " + index);

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

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

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

System.out.println (list.contains("Картошка") + "");

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

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

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

ArrayList myArrayList = new ArrayList(); myArrayList.add("Россия"); myArrayList.add("Польша"); myArrayList.add("Греция"); myArrayList.add("Чехия"); String[] array = <>; // конвертируем ArrayList в массив array = myArrayList.toArray(new String[myArrayList.size()]);

Интерфейс List

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

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

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

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

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

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

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

List numlist = Arrays.asList(1, 2, 5, 9, 11); System.out.println (numlist.get(2) + ""); // выводит число 5

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

List numlist = Arrays.asList(1, 2, 5, 9, 11); numlist.set(2, 33); // так можно numlist.add(34); // нельзя, ошибка во время исполнения System.out.println (numlist.get(2) + "");

Источник

How To Use remove() Methods for Java List and ListArray

How To Use remove() Methods for Java List and ListArray

Java List remove() method is used to remove elements from the list. ArrayList is the most widely used implementation of the List interface, so the examples here will use ArrayList remove() methods.

Java List remove() Methods

There are two remove() methods to remove elements from the List.

  1. E remove(int index ) : This method removes the element at the specified index and returns it. The subsequent elements are shifted to the left by one place. This method throws IndexOutOfBoundsException if the specified index is out of range. If the list implementations does not support this operation, UnsupportedOperationException is thrown.
  2. boolean remove(Object o ) This method removes the first occurrence of the specified Object . If the list doesn’t contain the given element, it remains unchanged. This method returns true if an element is removed from the list, otherwise false . If the object is null and list doesn’t support null elements, NullPointerException is thrown. UnsupportedOperationException is thrown if the list implementation doesn’t support this method.

Let’s look into some examples of remove() methods.

1. Remove the element at a given index

This example will explore E remove(int index ) :

ListString> list = new ArrayList>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); String removedStr = list.remove(1); System.out.println(list); System.out.println(removedStr); 

First, this code constructs and prints a list:

Then, this code executes remove(1) to remove the element at index 1 . Finally, it prints the new resulting list and also prints the removed element.

The B at index 1 has been removed.

2. IndexOutOfBoundsException with remove(int index) Method

This example will explore E remove(int index ) when the index exceeds the list:

ListString> list = new ArrayList>(); list.add("A"); String removedStr = list.remove(10); 

This code constructs a list with a length of 1 . However, when the code attempts to remove the element at index 10 :

Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 10 out of bounds for length 1 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:372) at java.base/java.util.ArrayList.remove(ArrayList.java:535) at com.journaldev.java.ArrayListRemove.main(ArrayListRemove.java:19)

This attempt throws the IndexOutOfBoundsException .

3. Unmodifiable List remove() UnsupportedOperationException Example

The List.of() method creates an immutable list, which can’t be modified.

ListString> list = List.of("a", "b"); System.out.println(list); String removedStr = list.remove(1); System.out.println(removedStr); 

First, this code constructs and prints an immutable list:

Then the code attempts to use the remove() method to remove the element at index 1 :

    Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)at java.base/java.util.ImmutableCollections$AbstractImmutableList.remove(ImmutableCollections.java:258)at TestRemoveList.main(TestRemoveList.java:12)

This attempt throws UnsupportedOperationException . It will also throw UnsupportedOperationException if you attempt list.remove("a") or list.remove("b") .

4. Removing an object from the list

This example will explore boolean remove(Object o ) :

ListString> list = new ArrayList>(); list.add("A"); list.add("B"); list.add("C"); list.add("C"); list.add("B"); list.add("A"); System.out.println(list); boolean isRemoved = list.remove("C"); System.out.println(list); System.out.println(isRemoved); isRemoved = list.remove("X"); System.out.println(list); System.out.println(isRemoved); 

First, this code constructs and prints a list:

Then, this code executes remove("C") to remove the first instance of C . Next, it prints the resulting list and also prints the boolean value of the operation - true :

Then, this code executes remove("X") , but there is no instance of X in the list, the list does not change. Finally, it prints the list and also prints the boolean value of the operation - false :

Conclusion

In this article, you learned about Java’s List method remove() .

Recommended Reading:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Remove Element from an ArrayList in Java

Learn to remove an item from an ArrayList using the remove() and removeIf() methods. The remove() method removes either the specified element or an element from the specified index. The removeIf() removes all elements matching a Predicate.

The ArrayList.remove() method is overloaded.

E remove(int index) boolean remove(E element))
  • The remove(int index) – removes the element at the specified index and returns the removed item.
  • remove(E element) – remove the specified element by value and returns true if the element was removed, else returns false.

The removeAll() accepts a collection and removes all elements of the specified collection from the current list.

boolean removeAll(Collection c)

The removeIf() accepts a Predicate to match the elements to remove.

boolean removeIf(Predicate filter)

2. Remove an Element by Specified Index

The remove(index) method removes the specified element E at the specified position in this list. It removes the element currently at that position, and all subsequent elements are moved to the left (will subtract one from their indices).

Note that List Indices start with 0.

ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles") ); System.out.println(namesList); //list size is 3 //Remove element at 1 index namesList.remove(1); System.out.println(namesList); //list size is 2
[alex, brian, charles] [alex, charles]

2. Remove Specified Element(s) By Value

The remove(Object) method removes the first occurrence of the specified element E in this list. As this method removes the object, the list size decreases by one.

ArrayList namesList = new ArrayList<>(Arrays.asList( "alex", "brian", "charles", "alex") ); System.out.println(namesList); namesList.remove("alex"); System.out.println(namesList);
[alex, brian, charles, alex] [brian, charles, alex]

To remove all occurrences of the specified element, we can use the removeAll() method. As this method accepts a collection argument, we first need to wrap the element to remove inside a List.

namesList.removeAll(List.of("alex"));

3. Remove Element(s) with Matching Condition

We can use another super easy syntax from Java 8 stream to remove all elements for a given element value using the removeIf() method.

The following Java program uses List.removeIf() to remove multiple elements from the arraylist in java by element value.

ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles", "alex") ); System.out.println(namesList); namesList.removeIf( name -> name.equals("alex")); System.out.println(namesList);
[alex, brian, charles, alex] [brian, charles]

Источник

Читайте также:  Платформы для изучения java
Оцените статью