How do you insert an element at the beginning of the list Java?

How to insert an element at beginning of the ArrayList in Java?

When we add elements to the ArrayList using theadd method, they are inserted at the end of the ArrayList. To insert element at the beginning or start of the ArrayList, use the overloaded add method of ArrayList which also accepts anindex parameter wherethe element needs to be inserted.

1
public void add(int index, E element)

This method inserts the element at the specified index in the ArrayList. If there is any element exists at the specified position, it shifts the existing elements along with any subsequent elements to the right (means increases their index by 1).

Java ArrayList insert an element at the beginning example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.javacodeexamples.collections.arraylist;
import java.util.ArrayList;
public class ArrayListInsertElementExample {
public static void main(String[] args) {
//create new ArrayList
ArrayList<String> aListNumbers
= new ArrayList<String>();
//we are going to add some numbers to ArrayList
aListNumbers.add("One");
aListNumbers.add("Two");
aListNumbers.add("Three");
/*
* To insert element at beginning of ArrayList
* use add method of ArrayList class with index 0
*/
aListNumbers.add(0, "Zero");
System.out.println("Element added at beginning of ArrayList");
//print ArrayList
System.out.println(aListNumbers);
}
}

Output

1
2
Element added at beginning of ArrayList
[Zero, One, Two, Three]

As you can see from the output, we specified index as 0 in the add method to insert element at the start of the ArrayList. List automatically shifted all the existing elements by increasing their index by 1.

Adding an Element to the Front of LinkedList in Java

A Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements are linked using pointers and addresses. Each element is known as a node. This article shows how to add an element to the front of LinkedList in Java.

Method 1: (Using user-defined method)

  • Allocate the memory to a new node.
  • Put in the element to be inserted in the allocated node.
  • Make the next of the new node as the head.
  • Move the head to point to the new node.

Example:




// Java program to Add an Element
// to the Front of LinkedList
import java.io.*;
class LinkedList {
// head reference
Node head;
// Node class
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// Inserting node at the front
public void insertfront(int data)
{
// Allocating and inserting the data in that node
Node new_node = new Node(data);
// Make the next of the newly allocated node to be
// the head
new_node.next = head;
// Now make the head to be the newly allocated node
head = new_node;
}
// Printing the List
public void print()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
public static void main(String args[])
{
// create a linkedlist
LinkedList l = new LinkedList();
// insert elements at the front
l.insertfront(6);
l.insertfront(5);
l.insertfront(8);
l.insertfront(9);
// print the linkedlist
l.print();
}
}
Output 9 8 5 6

Method 2: (Using addFirst(E e) method of LinkedList)



Declaration:

void addFirst(Object element)

Syntax:

LinkedList.addFirst(e)

Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at beginning of the list.

Return Value: This method does not return any value.




// Java program to Add an Element
// to the Front of LinkedList
import java.util.LinkedList;
class AddElementsAtTheFront {
public static void main(String args[])
{
// create a LinkedList
LinkedList<String> list = new LinkedList<String>();
// add elements at the front
list.addFirst("HI");
list.addFirst("HOW");
list.addFirst("ARE");
list.addFirst("YOU");
// print LinkedList
System.out.print(list);
}
}
Output [YOU, ARE, HOW, HI]

Method 3: (Using offerFirst(E e))

This method also inserts the specified element at the front of the list.

Declaration:

public boolean offerFirst(E e)

Syntax:

LinkedList.offerFirst(e)

Parameters: Here, e is the element to add

Return Value: This method returns true

Example:




// Java program to Add an Element
// to the Front of LinkedList
import java.util.LinkedList;
class AddingElementsAtTheFront {
public static void main(String args[])
{
// create a LinkedList
LinkedList<String> list = new LinkedList<String>();
// add elements at the front
list.offerFirst("HI");
list.offerFirst("HOW");
list.offerFirst("ARE");
list.offerFirst("YOU");
// print the LinkedList
System.out.print(list);
}
}
Output [YOU, ARE, HOW, HI]

How do you insert an element at the beginning of the list Java?




Article Tags :
Java
Java Programs
Technical Scripter
java-LinkedList
Technical Scripter 2020
Practice Tags :
Java

Java List

  • Java List Tutorial Video
  • List vs. Set
  • List Implementations
  • Create a List
  • Generic Lists
  • Insert Elements in a Java List
    • Insert null Values
    • Insert Elements at Specific Index
  • Insert All Elements From One List Into Another
  • Get Elements From a Java List
  • Find Elements in a List
    • Find Last Occurrence of Element in a List
  • Checking if List Contains Element
  • Remove Elements From a Java List
  • Remove All Elements From a Java List
  • Retain All Elements From One List in Another
  • List Size
  • Sublist of List
  • Convert List to Set
  • Convert List to Array
  • Convert Array to List
  • Sort List
    • Sort List of Comparable Objects
    • Sort List Using Comparator
  • Iterate List
    • Iterate List Using Iterator
    • Iterate List Using For-Each Loop
    • Iterate List Using For Loop
    • Iterate List Using Java Stream API
  • More Details in the Java List JavaDoc

Jakob Jenkov
Last update: 2020-02-29

The Java List interface, java.util.List, represents an ordered sequence of objects. The elements contained in a Java List can be inserted, accessed, iterated and removed according to the order in which they appear internally in the Java List. The ordering of the elements is why this data structure is called a List.

Each element in a Java List has an index. The first element in the List has index 0, the second element has index 1 etc. The index means "how many elements away from the beginning of the list". The first element is thus 0 elements away from the beginning of the list - because it is at the beginning of the list.

You can add any Java object to a List. If the List is not typed, using Java Generics, then you can even mix objects of different types (classes) in the same List. Mixing objects of different types in the same List is not often done in practice, however.

The Java List interface is a standard Java interface, and it is a subtype of the Java Collection interface, meaning List inherits from Collection.