As we have seen the implementations of a List are :
Let us see the ArrayList implementation first.
Let us say, we have a List that would contain three names, Mohan, Kriti and Salim.
We can use the add() Method to achieve the above.
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"); for (String data : x) { System.out.println(data); } } }
So, in the above code we have created an empty ArrayList.
Listx = new ArrayList<>();
Next, we have used the add() method to add the names, Mohan, Kriti and Salim to the ArrayList.
x.add("Mohan"); x.add("Kriti"); x.add("Salim");
Below is how the values are positioned in the List,
Then we are using the for each loop to print the above names on the screen.
for (String data : x) { System.out.println(data); }
And we get the below output,
Now, let us see the implementation using LinkedList. It is exactly similar to ArrayList.
Just like the above, let us say, we have a List that would contain three names, Mohan, Kriti and Salim.
We can use the add() Method to achieve the above.
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"); for (String data : x) { System.out.println(data); } } }