Arraylist.get in java: In the previous article we have discussed about Java ArrayList indexOf() Method with Example
In this article we are going to see the use Java ArrayList get() method along with suitable examples.
Java ArrayList get() Method with Example
get( ):
Java arraylist get: This java.util.ArrayList.get()
method is used retrieve the element present in specified position.
It returns the element, which is present in the specified position of the ArrayList
If the index is out of the size/range of the arraylist then it shows IndexOutOfBoundException
.
Syntax:
arrayListName.get()
Where,
arrayListName
refers to the name of your ArrayList.
Let’s see different examples to understand it more clearly.
Method-1: Java ArrayList get() Method – Example with String Type ArrayList
Approach:
- Create a new ArrayList of type String.
- Add string elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Now get the element from a specific position in the ArrayList using
get()
method. - Print the element.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a ArrayList of string datatype ArrayList<String> arr = new ArrayList<String>(); // Adding some elements to the ArrayList arr.add("Hello"); arr.add("this"); arr.add("is"); arr.add("an"); arr.add("example of get() method"); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // get the element from arrayList using specific position System.out.println("Element at index 1: " + arr.get(1)); } }
Output: The elements of ArrayList are: [Hello, this, is, an, example of get() method] Element at index 1: this
Method-2: Java ArrayList get() Method – Example with Integer Type ArrayList
Approach:
- Create a new ArrayList of type Integer.
- Add Integer elements into the ArrayList using the add() method.
- Display the ArrayList elements.
- Now get the element from a specific position in the ArrayList using
get()
method. - Print the element.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of Integer datatype ArrayList<Integer> arr = new ArrayList<Integer>(); // Adding some elements to the ArrayList arr.add(2); arr.add(52); arr.add(13); arr.add(17); arr.add(1); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // get the element from arrayList using specific position System.out.println("Element at index 1: " + arr.get(1)); } }
Output: The elements of ArrayList are: [2, 52, 13, 17, 1] Element at index 1: 52
If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.
Related Java Programs: