
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieve an Element from ArrayList in Java
An element can be retrieved from the ArrayList in Java by using the java.util.ArrayList.get() method. This method has a single parameter i.e. the index of the element that is returned.
A program that demonstrates this is given as follows
Example
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String args[]) throws Exception { List aList = new ArrayList(); aList.add("James"); aList.add("George"); aList.add("Bruce"); aList.add("Susan"); aList.add("Martha"); System.out.println("The element at index 3 in the ArrayList is: " + aList.get(3)); } }
The output of the above program is as follows
The element at index 3 in the ArrayList is: Susan
Now let us understand the above program. The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList.
Then the ArrayList.get() method is used to retrieve the element at index 3 and this is displayed. A code snippet which demonstrates this is as follows
List aList = new ArrayList(); aList.add("James"); aList.add("George"); aList.add("Bruce"); aList.add("Susan"); aList.add("Martha"); System.out.println("The element at index 3 in the ArrayList is: " + aList.get(3));
Advertisements