This example will explain how to add an element at beginning or at end of LinkedList object with addFirst and addLast methods in Java.
Source Code
import java.util.LinkedList;
public class AddElementOfLinkedList {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(1);
ll.add(2);
ll.add(3);
ll.addFirst(0);
//Same as the add() method
ll.addLast(4);
System.out.println(ll);
}
}
Output:
[0, 1, 2, 3, 4]