LinkedList add/insert elements
In this chapter you will learn:
Add element to LinkedList
The following methods add or insert value to a LinkedList
.
boolean add(E e)
Adds the the end.void add(int index, E element)
Adds at the specified position.boolean addAll(Collection<? extends E> c)
Adds all to the end.boolean addAll(int index, Collection<? extends E> c)
Inserts all at the specified position.void addFirst(E e)
Inserts at the beginning.void addLast(E e)
Appends the end.boolean offer(E e)
Adds as the tail (last element) of this list.boolean offerFirst(E e)
Inserts at the front of this list.boolean offerLast(E e)
Inserts at the end of this list.
The following code uses add()
and add(int index, E element)
methods to add elements to a LinkedList
.
import java.util.LinkedList;
// ja va2 s.com
public class Main{
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("A");
ll.add("B");
ll.add("ja v a2s.com");
ll.add("E");
ll.add("F");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
}
}
The output:
Add to the front of a LinkedList
The following code add elements to the start of the LinkedList.
import java.util.LinkedList;
// j ava 2 s. co m
public class Main{
public static void main(String args[]) {
LinkedList<String> ll = new LinkedList<String>();
ll.add("B");
ll.add("ja v a2s.com");
ll.addLast("E");
ll.add("F");
ll.add(1, "A2");
ll.addFirst("A");
System.out.println("Original contents of ll: " + ll);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Collections