The syntax of the get()
method is:
arraylist.get(int index)
Here, arraylist is an object of the ArrayList class.
get() Parameter
The get()
method takes single parameter.
- index - position of the element to be accessed
get() Return Value
- returns the element present in the specified position.
- raises
IndexOutOfBoundsException
, if index is out of the range.
Example 1: get() Method with String ArrayList
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<String> languages = new ArrayList<>();
// insert element to the arraylist
languages.add("JavaScript");
languages.add("Java");
languages.add("Python");
System.out.println("Programming Languages: " + languages);
// access element at index 1
String element = languages.get(1);
System.out.println("Element at index 1: " + element);
}
}
Output
Programming Languages: [JavaScript, Java, Python] Element at index 1: Java
In the above example, we have created an arraylist named languages. Here, the get()
method is used to access the element present at index 1.
Example 2: get() Method with Integer ArrayList
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
// insert element to the arraylist
numbers.add(22);
numbers.add(13);
numbers.add(35);
System.out.println("Numbers ArrayList: " + numbers);
// return element at position 2
int element = numbers.get(2);
System.out.println("Element at index 2: " + element);
}
}
Output
Numbers ArrayList: [22, 13, 35] Element at index 2: 35
Here, the get()
method is used to access the element at index 2.
Note: We can also get the index number of an element using the indexOf()
method. To learn more, visit Java ArrayList indexOf().
Also Read: