As we have seen the implementations of a List are :
Let us see the ArrayList implementation first.
We have the List with three values, Mohan, Kriti and Salim. And we want to access the second element i.e. Kriti.
import java.util.ArrayList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new ArrayList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); System.out.println(x.get(1)); } }
So, in the above code we have created a List,
Listx = 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
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.
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.
import java.util.LinkedList; import java.util.List; public class MyApplication { public static void main(String[] args) { Listx = new LinkedList<>(); x.add("Mohan"); x.add("Kriti"); x.add("Salim"); System.out.println(x.get(1)); } }