ArrayList.listIterator(int): This method is available in java.util.ArrayList class of Java.
Syntax:
ListIterator<E> java.util.ArrayList.listIterator(int index)
This method takes one argument of type int as its parameter. This method returns a list iterator over the elements in this list starting at the specified position in the list.
Parameters: One parameter is required for this method.
index: index of the first element to be returned from the list iterator.
Returns: a list iterator over the elements in this list starting at the specified position in the list.
Throws:
IndexOutOfBoundsException - if the index is out of range(index < 0 || index > size())
Approach 1: When no exceptions
Java
import java.util.ArrayList;public class ArrayListlistIterator {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(2);arr.add(3);System.out.println(arr.listIterator(0));}}
Output:
java.util.ArrayList$ListItr@26f0a63f
Approach 2: IndexOutOfBoundsException
Java
import java.util.ArrayList;public class ArrayListlistIterator {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(2);arr.add(3);System.out.println(arr.listIterator(4));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756) at java.base/java.util.ArrayList.listIterator(ArrayList.java:923)
No comments:
Post a Comment