StudyPain



add at index - Java ArrayList Method




TLDR

Inserts an element at a specific index in the list.


// Method Signature
void add(int index, E element)

Image of an element being added to an index in an arrayList



Usage

The ArrayList add at index inserts an element at a specific index in the list.


If any elements are to the right of the index, they will be shifted to the right.


// Method Signature
void add(int index, E element)

// Code Example

// Creates an ArrayList of Integers
var list = new ArrayList<>(List.of(2, 4, 6));

// prints [2, 4, 6]
System.out.println(list);

// add 5 at index 1
list.add(1, 5);

// print [2, 5, 4, 6]
System.out.println(list);

In the code example above, we create an ArrayList of numbers and print out the list’s current value of [2, 4, 6].


Next, we call the method add with an integer of 1 and 5. The integer 1 is the index where we want to add our integer 5.


As a result of the method call, the list shifts elements 4 and 6 to the right, and inserts 5 at index 1. The final result is [2, 5, 4, 6].



Parameters

This method takes two parameters called index and element.


The first parameter is index:


The second parameter is element:



Returns

Void - There is no return value for the method.



Throws

IndexOutOfBoundsException:



Code Example

Inserts an element at the end of a list:


// Inserts at the end of a list

// creates an ArrayList of Characters
var list = new ArrayList<>(List.of('a', 'b'));

// prints [a, b]
System.out.println(list);

// adds 'c' at the result of list.size()
// list.size() == 2
list.add(list.size(), 'c');

// prints [a, b, c]
System.out.println(list);

Inserts an element at the beginning of a list:


// Insert at index 0

// Creates an ArrayList of Strings
var list = new ArrayList<>(List.of("hi", "bye"));

// prints [hi, bye]
System.out.println(list);

// adds "greet" at index 0
list.add(0, "greet");

// prints [greet, hi, bye]
System.out.println(list);
Privacy Policy Cookie Policy Terms of Use Disclaimer