List add() Method in Java with Examples
Last Updated :
16 Feb, 2024
The List add() method adds (appends) an element to a list. It can be used for both ArrayList and LinkedList.
Example of List add() Method:
Java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class GFG {
public static void main (String[] args) {
List<String> newList = new ArrayList<>();
newList.add( "Hello" );
newList.add( "World" );
System.out.println(newList);
}
}
|
Output:
[Hello, World]
Syntax
The add method has two overloads. It can be used with the index parameter and without the index parameter:
Method |
Description |
add(E element) |
It is used to add(append ) a new element at the end of the list. |
add(int Index, E element) |
It is used to add a new element at a specific index. |
Parameters
- element- Element to be added to the list.
- Index- Index at which element needs to be added.
Returns
It returns true if the specified element is appended and the list changes.
Exceptions
- ClassCastException- When the class of an element prevents it from being added to the list.
- NullPointerException- When the element is Null and the list doesn’t allow a null value.
- UnsupportedOperationException- When the list doesn’t support add operation.
- IllegalArgumentException- When a property of an element prevents it from being added to a list.
Java List add() Method Examples
Let’s look at some examples of how to use the list add() method in Java.
Example 1:
How to add an element to a list in Java using the add(Element E) method:
Java
import java.util.*;
public class GfG {
public static void main(String[] args)
{
List<Integer> l = new ArrayList<>();
l.add( 10 );
l.add( 15 );
l.add( 20 );
System.out.println(l);
}
}
|
Example 2:
How to add an element at a specific index in a list in Java using the add(int I, Element E) method.
Java
import java.util.*;
public class GfG {
public static void main(String[] args)
{
List<Integer> l = new ArrayList();
l.add( 10 );
l.add( 15 );
l.add( 1 , 20 );
System.out.println(l);
}
}
|
Example 3:
How to add an element to a LinkedList in Java using the add() method.
Java
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args)
{
List<Integer> ll = new LinkedList<>();
ll.add( 100 );
ll.add( 200 );
ll.add( 300 );
ll.add( 400 );
ll.add( 500 );
System.out.println(ll);
}
}
|
Output
[100, 200, 300, 400, 500]
Reference: Official Oracle Docs
Whether you are a beginner starting Java programming or an experienced looking to brush up on your Java skills, this tutorial will provide you with a deep understanding of the add function and its uses in Java.
The add method in Java is a fundamental function for list manipulation. With this guide, you can easily add/append a new element to a list using the add method.
Read More: Java List Methods
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...