English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList get() method returns the element existing at the specified position.
The syntax of the get() method is:
arraylist.get(int index)
index - Position of the element to be accessed
Returns the element existing at the specified position.
Note: If the index is out of range, the get() method will throw an exception exception IndexOutOfBoundsException.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<String> languages = new ArrayList<>(); //Insert Element into ArrayList languages.add("JavaScript"); languages.add("Java"); languages.add("Python"); System.out.println("Programming languages: " + languages); //Access index1element at the location String element = languages.get(1); System.out.println("Index1: element: " + element); } }
Output Result
Programming languages: [JavaScript, Java, Python] Index1: Java
In the above example, we created an array list named languages. Here, the get() method is used to access the element at the index1elements exist at the location.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); // Insert Element into ArrayList numbers.add(22); numbers.add(13); numbers.add(35); System.out.println("Number ArrayList: " + numbers); //Return Position2element int element = numbers.get(2); System.out.println("Index2element: " + element); } }
Output Result
Number ArrayList: [22, 13, 35] Index2: element: 35
Here, the get() method is used to access the element at the index2element at the location.
NoteWe can also use the indexOf() method to obtain the index value of the element (number). For more information, please visitJava ArrayList indexOf().