Удаление элемента из указанного индекса в Java ArrayList

Опубликовано: 30 Января, 2022

Метод remove (int index), присутствующий в классе java.util.ArrayList, удаляет элемент в указанной позиции в этом списке и сдвигает все последующие элементы влево (т. Е. Вычитает единицу из их индексов).

Синтаксис:

 общедоступный удаленный элемент удалить (индекс int)

Параметры: индекс удаляемого элемента.

Тип возврата: этот метод возвращает элемент, который был удален из списка.

Исключение: этот метод вызывает исключение IndexOutOfBoundsException, если индекс выходит за пределы допустимого диапазона.

When we will try to remove an element at the index which is greater than or equal to the size of the array list, the editor will give us the IndexOutOfBound Exception on running.

Java

// Java program to show the exception
// of remove() method
  
import java.util.ArrayList;
  
public class ArrayListDemo {
   public static void main(String[] args) {
        
      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
  
      // use add() method to add elements in the deque
      arrlist.add(20);
      arrlist.add(15);
      arrlist.add(30);
      arrlist.add(45);
  
      System.out.println("Size of list: " + arrlist.size());
        
      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
        
      // Removes element at 5th position
      // which is not present in the list
      // and will therefore give IndexOutOfBound exception
      arrlist.remove(4);
  
      System.out.println("Now, Size of list: " + arrlist.size());
        
      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }
   }
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 4

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .