Friday, May 10, 2024
HomeProgrammingDifferent ways to add elements to an ArrayList in Java

Different ways to add elements to an ArrayList in Java

How to add elements to an ArrayList in Java:

Java ArrayList provides a method called add with which elements are attached to the ArrayList. This method is used to add an element to the end of the ArrayList or we can use it to add the element at a specific position.

Let’s learn how to use this with examples.

Add an element to the end of the ArrayList:

The add method is defined as:

Where, e is the element to add to the ArrayList. It adds the element to the end of the ArrayList And come back WHERE.

Let’s try it with an example:

import java.util.ArrayList;  

public class Main {  
    public static void main(String[] args) {  
        ArrayList<Integer> givenList = new ArrayList<>();  
        givenList.add(1);  
        givenList.add(2);  
        givenList.add(3);  

        System.out.println(givenList);  
    }  
}

In this example we have a empty ArrayList and used it add() to add three digits to the ArrayList. Running this program will print the output below:

Example 2: Add an element at a specific position:

We can use the add method to add an element at a specific position. Below is the method definition:

public void add(int index, E e)

Here,

  • Table of contents is the index at which the element should be inserted.
  • e is the element to be inserted.

Note that this method will throw IndexOutOfBoundsException if it is given Table of contents is invalid. For example, if we pass a negative Table of contents or a value greater than the size of the ArrayListit will throw IndexOutOfBoundsException.

Let’s try it with an example:

import java.util.ArrayList;  

public class Main {  
    public static void main(String[] args) {  
        ArrayList<Integer> givenList = new ArrayList<>();  
        givenList.add(0);  
        givenList.add(1);  
        givenList.add(3);  

        givenList.add(2, 2);  

        System.out.println(givenList);  
    }  
}

At first it added itself 0.1 And 3 to the ArrayList. It added 2 at index 2. So the final ArrayList is becoming:

As you can see here, it has been added 2 to the ArrayList.

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments

бнанс Створити акаунт on The Interview Process in Clark, Pampanga
Binance注册奖金 on Venus in Scorpio