.get()
Published Feb 1, 2023
Contribute to Docs
The .get()
method retrieves the element at some index in an ArrayList
.
Syntax
arrayListInstance.get(index);
The element at index index
in arrayListInstance
is returned. If the index is out of range, an IndexOutOfBoundsException
will be thrown.
Example
In the example below, an empty ArrayList
, studentList
, is created and populated with several elements of type String
. The .get()
method retrieves the students at indexes 0 and 1.
// Students.javaimport java.util.ArrayList;public class Students {public static void main(String[] args) {ArrayList<String> studentList = new ArrayList<>();// Add new values to the studentListstudentList.add("John");studentList.add("Lily");studentList.add("Samantha");studentList.add("Tony");// `.get()` method extracts the element's valueString StudentOne = studentList.get(0);String StudentTwo = studentList.get(1);// Output ArrayList and searched elementsSystem.out.println("ArrayList: " + studentList);System.out.println("Searched Elements: " + StudentOne + " and " + StudentTwo);}}
The output will look like this:
ArrayList: [John, Lily, Samantha, Tony]Searched Elements: John and Lily
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours