Add Elements to a LinkedList in Java

Exercise:

Write a Java Program to add elements to a LinkedList.

1. Add using add()

Click Here to View the Solution!
import java.util.LinkedList;

public class add {
    public static void main(String[] args){
        LinkedList<String> languages = new LinkedList<>();

        // Add elements to LinkedList
        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");
        languages.add("PHP");
        System.out.println("LinkedList: " + languages);
    }
}
Click Here to View the Output!
LinkedList: [Java, Python, JavaScript, PHP]
Click Here to View the Explanation!
  • In this program, first a String type LinkedList called languages is created.
  • Elements are added to the rear of this LinkedList using add() method.
  • The LinkedList is then printed onto the screen.

2.Add element at the specified index

Click Here to View the Solution!
import java.util.LinkedList;

public class add{
    public static void main(String[] args){
        LinkedList<String> languages = new LinkedList<>();
        languages.add("Swift");
        languages.add("Python");
        languages.add("PHP");
        languages.add("HTML");
        System.out.println("LinkedList: " + languages);

        // add element at the specified position
        languages.add(0, "Java");
        System.out.println("Updated LinkedList: " + languages);
    }
}
Click Here to View the Output!
LinkedList: [Swift, Python, PHP, HTML]
Updated LinkedList: [Java, Swift, Python, PHP, HTML]
Click Here to View the Explanation!
  • In this example, a string type LinkedList called languages is created firstly.
  • Elements are added to this LinkedList using the add() method and then the list is printed on the screen.
  • Next, an element is specified to be added at the 0 index of the LinkedList as seen in the expression: languages.add(0, "Java");
  • Here the index is an optional parameter and elements can be added at any index in this way.
  • The updated LinkedList is then printed on the screen.

3. Add using listIterator() method

Click Here to View the Solution!
 import java.util.ArrayList;
 import java.util.ListIterator;
  
 public class Add{
   public static void main(String[] args) {
     ArrayList<String> languages = new ArrayList<>();
     ListIterator<String> listIterate = languages.listIterator();
     listIterate.add("Java");
     listIterate.add("Python");
     listIterate.add("Javascript");
     System.out.println("LinkedList: " + languages);
   }
 } 
Click Here to View the Output!
LinkedList: [Java, Python, Javascript]
Click Here to View the Explanation!
  • In this example, a String type ArrayList called languages is created firstly.
  • Then an instance of ListIterator class called listIterate is created.
  • add() method is used to add elements to listIterate.
  • The updated list is then printed on the screen.

%d bloggers like this: