Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Accessing List


As we have seen the implementations of a List are :

  1. ArrayList

  2. LinkedList


Let us see the ArrayList implementation first.


Accessing the elements of the List using get() method


We have the List with three values, Mohan, Kriti and Salim. And we want to access the second element i.e. Kriti.


Example :



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

public class MyApplication {
    public static void main(String[] args) {

        List x = new ArrayList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");
        
        System.out.println(x.get(1));
    }
}


Output :



  John

So, in the above code we have created a List,


List x = new ArrayList<>();

And added three values to it.


x.add("Mohan");
x.add("Kriti");
x.add("Salim");

Now, let us see, how the values are positioned in the List

Spring_Boot

So, as we can see the elements are positioned as 0, 1 and 2. And if we want to access the second element, we can refer to the position 1 using the get() method (i.e. x.get(1)).


And the print statement prints the value of the second element of the List (i.e. Kriti).


System.out.println(x.get(1));

Next, let us see the implementation using LinkedList. It is exactly similar to ArrayList.


Accessing the elements of the List using get() method


As seen above, we have the List with three values, Mohan, Kriti and Salim. And we want to access the second element i.e. Kriti.


Example :



import java.util.LinkedList;
import java.util.List;

public class MyApplication {
    public static void main(String[] args) {

        List x = new LinkedList<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");
        
        System.out.println(x.get(1));
    }
}


Output :



  John