- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I insert elements in a Java list?
Solution
We can insert element to an array list easily using its add() method.
Syntax
boolean add(E e)
Appends the specified element to the end of this list.
Type Parameter
E − The runtime type of the element to be added.
Parameters
e − Element to be appended to this list
Returns
It returns true.
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.
Example
The following example shows how to insert elements to the list using add() method.
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { // Create a list object List<String> list = new ArrayList<>(); // add elements to the list list.add("A"); list.add("B"); list.add("C"); // print the list System.out.println(list); } }
Output
This will produce the following result −
[A, B, C]
- Related Articles
- How do I insert elements at a specific index in Java list?
- How do I insert all elements from one list into another in Java?
- How do I remove multiple elements from a list in Java?
- How do I insert an item between two items in a list in Java?
- How do I empty a list in Java?
- How do I search a list in Java?
- How can I find elements in a Java List?
- How can I get elements from a Java List?
- How do I insert a NULL value in MySQL?
- How to insert elements in C++ STL List?
- How do I set the size of a list in Java?
- How do I turn a list into an array in Java?
- How do I find an element in Java List?
- How do I find the size of a Java list?
- How do I get length of list of lists in Java?

Advertisements