public
E get(int index)
Returns
the element at the specified position in this list.
import java.util.*; class ArrayListGet{ public static void main(String args[]){ ArrayList<Integer> myList; myList = new ArrayList<Integer> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); System.out.println("Elements in myList are " + myList); System.out.println("\nElement at index 1 is " + myList.get(1)); } }
Output
Elements in myList are [10, 20, 30, 40] Element at index 1 is 20
1. Throws
IndexOutOfBoundsException, if index is out of range
import java.util.*; class ArrayListGetIndexOut{ public static void main(String args[]){ ArrayList<Integer> myList; myList = new ArrayList<Integer> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); System.out.println("Elements in myList are " + myList); System.out.println("\nElement at index -1 is " + myList.get(-1)); } }
Output
Elements in myList are [10, 20, 30, 40] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(ArrayList.java:371) at java.util.ArrayList.get(ArrayList.java:384) at ArrayListGetIndexOut.main(ArrayListGetIndexOut.java:15)
No comments:
Post a Comment