LinkedList add() Method in Java

The add(E element) of LinkedList appends the specified element at the end of the list. We can also add an element at a specific position using the add(int index, E element) method.

Syntax 1

public boolean add(E e)

Parameters

e is the element to be added to the linked-list

Return Value

It returns true on the successful addition of the element in this linked list.

Syntax 2

public void add(int index, E element)

Parameters

the index is the position at which element has to be inserted
element is the element to be added in this linked-list

Exception

It throws IndexOutOfBoundsException if the index is out of range. (index < 0 || index > size())

Program 1

import java.util.LinkedList;

public class LinkedListAddExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
	}
}

Output

Linked List elements: [5, 7, 9, 11]

Program 2

import java.util.LinkedList;

public class LinkedListAddExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);

		oddNumbers.add(2, 15);
		System.out.println("Linked List elements after adding element at index 2: " + oddNumbers);

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Linked List elements after adding element at index 2: [5, 7, 15, 9, 11]

Program 3

import java.util.LinkedList;

public class LinkedListAddExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);

		oddNumbers.add(6, 15);
	}
}

Output

Linked List elements: [5, 7, 9, 11]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 4
	at java.util.LinkedList.checkPositionIndex(LinkedList.java:560)
	at java.util.LinkedList.add(LinkedList.java:507)
	at LinkedListAddExample.main(LinkedListAddExample.java:17)
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published.