Add elements in LinkedList

We can use add() method of LinkedList to insert new elements to LinkedList

There are 6 overloaded “add” methods defined in LinkedList


1) boolean add(Object o);
2) void add(int index, Object o);
3) boolean addAll(Collection c);
4) boolean addAll(int index,Collection c);
5) void addFirst(Object o);
6) void addLast(Object o);

We have already discussed first 4 methods in the above list in the ArrayList article, and its same for LinkedList as well.
Please refer add-elements-in-arraylist article for the same

Let’s discuss last 2 methods with example


1) Void addFirst(Object o)
2) Void addLast(Object o)

addFirst : This method is used to add an element at the beginning of the list
addLast : This method is used to add an element at the end of the list

Example :

  1. import java.util.*;
  2. public class LinkedListAdd {
  3.     public static void main(String[] args) {
  4.     LinkedList<String> list = new LinkedList<String>();
  5.     list.add("Java");
  6. list.add("c++");
  7. list.add("python");
  8. System.out.println("Linked list before performing add first and add last ");
  9. System.out.println(list);
  10. //Performing add first and add last
  11. list.addFirst("Hai");
  12. list.addLast("Bye");
  13. System.out.println("Linked list after performing add first and add last ");
  14. System.out.println(list);
  15.     }
  16. }
import java.util.*;
public class LinkedListAdd {
    public static void main(String[] args) {
    LinkedList<String> list = new LinkedList<String>();
    list.add("Java");
list.add("c++");
list.add("python");
System.out.println("Linked list before performing add first and add last ");
System.out.println(list);
//Performing add first and add last
list.addFirst("Hai");
list.addLast("Bye");
System.out.println("Linked list after performing add first and add last ");
System.out.println(list);
    }
}


We can see in the output that,
addFirst has added element at the beginning of the list
addLast has added element at the end of the list

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on