Q:

Get an element/object from given index of a List in Java

belongs to collection: Java List Programs

0

Given a list of integers and we have to access/retrieve element/object from given index from the list in Java.

To get the element from given index - we use List.get() method, it is a library method of the List, which returns object/element from given index.

Syntax:

    List.get(index);

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    // creating a list of integers
    List < Integer > int_list = new ArrayList < Integer > ();

    //adding some of the elements
    int_list.add(10);
    int_list.add(20);
    int_list.add(30);
    int_list.add(40);
    int_list.add(50);

    //printing the empty list 
    System.out.println("Element at " + 0 + " index = " + int_list.get(0));
    System.out.println("Element at " + 1 + " index = " + int_list.get(1));
    System.out.println("Element at " + 2 + " index = " + int_list.get(2));
    System.out.println("Element at " + 3 + " index = " + int_list.get(3));
    System.out.println("Element at " + 4 + " index = " + int_list.get(4));
  }
};

Output

Element at 0 index = 10
Element at 1 index = 20
Element at 2 index = 30
Element at 3 index = 40
Element at 4 index = 50

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Replace an element at given index of a List with n... >>
<< Add object/element to the List at specified index ...