What is the LinkedList.add method in Java?

What is the LinkedList.add method in Java? Answer

What is the add method?

The add method of the LinkedList class adds an element to the end of the LinkedList.

LinkedList

LinkedList is a collection of linear data elements. Each element, or node, contains data and reference parts.

  • The data part has the value
  • The reference part has the address link to the next element

The elements are not indexed so random access, such as Array, is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is a doubly-linked list implementation of the List and Deque interfaces.

The LinkedList class present in the java.util package.

Syntax

public boolean add(E e);

Parameters

The add method takes the element to be added to the list as a parameter.

Return value

The add method returns true if the element is added to the list.

Code

The code below demonstrates how to use the add method.

import java.util.LinkedList;
class LinkedListAdd {
    public static void main( String args[] ) {
      LinkedList<String> list = new LinkedList<>();
      list.add("hello");
      System.out.println("The list is " + list);
      list.add("hi");
      System.out.println("The list is " + list);
    }
}

Explanation

In the code above,

  • In line number 1 we import the LinkedList class.
import java.util.LinkedList;
  • In line number 4 we create a LinkedList object with the name list.
LinkedList<String> list = new LinkedList<>();
  • In line number 5 we use the add method of the list object to add an element ("hello") to the list.
  • Then we print the list.
list.add("hello");
list; // ["hello"]
  • In line number 7 we use the add method of the list object to add another element ("hi") to the list.
  • Then we print the list.
list.add("hi");
list; // ["hello", "hi"]
What is the LinkedList.add method in Java? Review:

In our experience, we suggest you solve this What is the LinkedList.add method in Java? and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the What is the LinkedList.add method in Java?

Find on Educative

Conclusion:

I hope this What is the LinkedList.add method in Java? would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.