
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Element to a List in Java
We can use add() methods of List to add elements to the list.
1. Use add() method without index.
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
Parameters
e − Element to be appended to this list.
Returns
True (as specified by Collection.add(E)).
Throws
UnsupportedOperationException − If the add operation is not supported by this list.
ClassCastException − If the class of the specified element prevents it from being added to this list.
NullPointerException − If the specified element is null and this list does not permit null elements.
IllegalArgumentException − If some property of this element prevents it from being added to this list.
2. Use add() with index parameter to add an element at particular location.
void add(int index, E element)
Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Parameters
index − Index at which the specified element is to be inserted.
element − Element to be inserted.
Throws
UnsupportedOperationException − If the add operation is not supported by this list.
ClassCastException − If the class of the specified element prevents it from being added to this list.
NullPointerException − If the specified element is null and this list does not permit null elements.
IllegalArgumentException − If some property of this element prevents it from being added to this list.
IndexOutOfBoundsException − If the index is out of range (index < 0 || index > size()).
Example
Following is the example showing the usage of add() methods −
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(5); list.add(6); System.out.println("List: " + list); list.add(3, 4); System.out.println("List: " + list); try { list.add(7, 7); } catch(IndexOutOfBoundsException e) { e.printStackTrace(); } } }
Output
This will produce the following result −
List: [1, 2, 3, 5, 6] List: [1, 2, 3, 4, 5, 6] java.lang.IndexOutOfBoundsException: Index: 7, Size: 6 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:788) at java.base/java.util.ArrayList.add(ArrayList.java:513) at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:22)