Как заменить элемент в arraylist java
Перейти к содержимому

Как заменить элемент в arraylist java

  • автор:

Как заменить элемент в arraylist java

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:

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.

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.

Replace an Existing Item in ArrayList

Learn to update or replace an existing element in ArrayList with a new specified element or value, using set (int index, Object newItem) method.

1. Replacing an Existing Item

To replace an existing item, we must find the item’s exact position (index) in the ArrayList. Once we have the index, we can use set() method to update the replace the old element with a new item.

  • Find the index of an existing item using indexOf() method.
  • Use set(index, object) to update with the new item.

Note that the IndexOutOfBoundsException will occur if the provided index is out of bounds.

2. Example

The following Java program contains four strings. We are updating the value of “C” with “C_NEW”.

We can make the whole replacing process in a single statement as follows:

Замена элемента ArrayList в Java

Вы можете заменить элемент ArrayList в Java, используя метод set() класса Collections. Этот метод принимает два параметра: целочисленный параметр, указывающий индекс заменяемого элемента и заменяемый элемент.

Пример

Средняя оценка 3 / 5. Количество голосов: 8

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

Помогите улучшить статью.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

How to replace an element of ArrayList in Java? Example

Though you can also use the set() method with the List returned by Arrays.asList() method as oppose to add() and remove() which is not supported there. You just need to be careful with the index of elements. For example, if you want to replace the first element then you need to call set(0, newValue) because similar to an array, the ArrayList index is also zero-based.

Now, the questions come why do you want to replace an element in the ArrayList? Why not just remove the element and insert a new one? Well, obviously the remove and insert will take more time than replace.

The java.util.ArrayList provides O(1) time performance for replacement, similar to size() , isEmpty() , get() , iterator() , and listIterator() operations which runs in constant time.

Now, you may wonder that why set() gives O(1) performance but add() gives O(n) performance, because it could trigger resizing of the array, which involves creating a new array and copying elements from the old array to the new array. You can also see these free Java courses to learn more about the implementation and working of ArrayList in Java.

Replacing an existing object in ArrayList

How to replace an element of ArrayList in Java? Example

Java Program to replace elements in ArrayList

You can see that initially, we have a list of 5 books and we have replaced the second element by calling the set(1, value) method, hence in the output, the second book which was «Clean Coder» was replaced by «Introduction to Algorithms».

That’s all about how to replace existing elements of ArrayList in Java. The set() method is perfect to replace existing values just make sure that the List you are using is not immutable. You can also use this method with any other List type like LinkedList. The time complexity is O(n) because we are doing index-based access to the element.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *