

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How can I get elements from a Java List?
Elements can be retrieved from a list using get() method.
Syntax
E get(int index)
Returns the element at the specified position in this list.
Parameters
index − Index of the element to return.
Returns
The element at the specified position in this list.
Throws
IndexOutOfBoundsException − If the index is out of range (index < 0 || index >= size()).
Here index represents the index of the element E in the list. It throws IndexOutOfBoundsException if index is out of range.
Example
Following is the example getting elements from a list using get() method −
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); System.out.println("List: " + list); System.out.println("List(1): " + list.get(1)); try { System.out.println("List(3): " + list.get(3)); }catch(IndexOutOfBoundsException e) { System.out.println(e); } } }
Output
This will produce the following result −
List: [A, B, C] List(1): B java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
- Related Questions & Answers
- How can I find elements in a Java List?
- How do I remove multiple elements from a list in Java?
- How do I insert elements in a Java list?
- How can I get a list of locally installed Python modules?
- How do I insert all elements from one list into another in Java?
- How can I create a dropdown menu from a List in Tkinter?
- How do I insert elements at a specific index in Java list?
- How can I get a list of databases and collections on a MongoDB server?
- Java Program to Get First and Last Elements from an Array List
- How can I get the list of columns from a table in the database we are currently using?
- Java program to remove duplicates elements from a List
- C# Program to get the first three elements from a list
- How can I get the selected value of a drop-down list with jQuery?
- How can I get the list of files in a directory using C/C++?
- Get last N elements from given list in Python
Advertisements