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




Java - Insert in List


As we have seen the implementations of a List are :

  1. ArrayList

  2. LinkedList


Let us see the ArrayList implementation first.


How to insert a new Items in ArrayList?


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.


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");
        
        for (String data : x) {
            System.out.println(data);
        }
    }
}


Output :



  Mohan
  Kriti
  Salim

So, in the above code we have created an empty ArrayList.


List x = 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,

Spring_Boot

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,

Output :



  Mohan
  Kriti
  Salim

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


How to insert a new Items in LinkedList?


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.


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");

        for (String data : x) {
            System.out.println(data);
        }
    }
}


Output :



  Mohan
  Kriti
  Salim