public
E remove(int index)
Removes
the element at the specified position in this list. Shifts any
subsequent elements to the left.
import java.util.*; class ArrayListRemoveAtIndex{ public static void main(String args[]){ ArrayList<Integer> myList; myList = new ArrayList<> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); System.out.println("Elements in myList are"); System.out.println(myList); System.out.println("\nRemove Element at index 2"); System.out.print("Element removed is "); System.out.println(myList.remove(2)); System.out.println("\nElements in myList are"); System.out.println(myList); } }
Output
Elements in myList are [10, 20, 30, 40] Remove Element at index 2 Element removed is 30 Elements in myList are [10, 20, 40]
1. Throws
IndexOutOfBoundsException, if index is out of range
import java.util.*; class ArrayListRemoveAtIndexOut{ public static void main(String args[]){ ArrayList<Integer> myList; myList = new ArrayList<> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); System.out.println("Elements in myList are"); System.out.println(myList); System.out.println("\nRemove Element at index 5"); System.out.print("Element removed is "); System.out.println(myList.remove(5)); System.out.println("\nElements in myList are"); System.out.println(myList); } }
Output
Elements in myList are [10, 20, 30, 40] Remove Element at index 5 Element removed is Exception in thread "main" java.lang.IndexOutOfBoundsExceptio n: Index: 5, Size: 4 at java.util.ArrayList.rangeCheck(ArrayList.java:638) at java.util.ArrayList.remove(ArrayList.java:477) at ArrayListRemoveAtIndexOut.main(ArrayListRemoveAtIndexOut.java:19)
No comments:
Post a Comment