In this guide, you will learn about the List get() method in Java programming and how to use it with an example.
1. List get() Method Overview
Definition:
The get() method of the Java List interface retrieves the element at a specified position in the list.
Syntax:
list.get(int index)
Parameters:
int index - the index of the element to be retrieved.
Key Points:
- Returns the element present at the specified position in the list.
- Throws IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).
- The index is 0-based, so the first element is at index 0, the second at index 1, and so on.
2. List get() Method Example
import java.util.ArrayList;
import java.util.List;
public class ListGetExample {
public static void main(String[] args) {
// Create a new ArrayList with some elements
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println(colors.get(1)); // Outputs: Green
try {
System.out.println(colors.get(3)); // This line will throw an exception
} catch (IndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
}
// Demonstrate the 0-based index nature of the list
System.out.println(colors.get(0)); // Outputs: Red
}
}
Output:
Green Index out of bounds! Red
Explanation:
In the provided example:
1. We initiated an ArrayList of strings with three color names.
2. We then used the get() method to retrieve colors based on their positions in the list.
3. We demonstrated the exception that is thrown if an attempt is made to access an index out of bounds.
4. Lastly, we highlighted that the list indexing starts from 0 by fetching the first element of the list.
The get() method provides an efficient way to retrieve a specific element from a list based on its position. Being aware of the 0-based index and potential IndexOutOfBoundsException can help in using the method more effectively.
Related Java List methods
Java List add() example
Java List clear() example
Java List contains() example
Java List get() example
Java List indexOf() example
Java List remove() example
Java List size() example
Java List toArray() example
Comments
Post a Comment
Leave Comment