List get() Method Example

1. Introduction

The List interface in Java represents an ordered collection (also known as a sequence). A very common operation in the List interface is the get(int index) method, which retrieves the element at the specified position in the list. This method is crucial in iterating over, accessing, and modifying elements within the list.

2. Program Steps

1. Create a List of type String.

2. Populate the List with some elements.

3. Access elements using the get method by specifying their indexes.

3. Code Program

import java.util.ArrayList;
import java.util.List;

public class ListGetMethodExample {
    public static void main(String[] args) {
        // Step 1: Creating a List of Strings
        List<String> names = new ArrayList<>();

        // Step 2: Adding elements to the List
        names.add("Ramesh");
        names.add("Prabas");
        names.add("Sanjay");
        names.add("Vijay");

        // Step 3: Accessing elements from the List
        // Accessing the first element (index 0)
        System.out.println("First name in the list: " + names.get(0));

        // Accessing the third element (index 2)
        System.out.println("Third name in the list: " + names.get(2));
    }
}

Output:

First name in the list: Ramesh
Third name in the list: Sanjay

Explanation:

1. A List named names is created and populated with Indian names. This list is an instance of ArrayList, which is a common implementation of the List interface.

2. The add method is used to insert names into the list. The list maintains these names in the order they are added.

3. The get method is used to access elements from the list. When names.get(0) is called, it retrieves the first element of the list, which is "Ramesh". Similarly, names.get(2) retrieves the third element, which is "Sanjay". The indexing for a list starts at 0, making the first element accessible at index 0, the second at index 1, and so on.

Comments