We can add elements to the list using the add() method of List.
boolean add(E e)
Append the specified element to the end of this list (optional operation).
e strong> - The element to append to this list.
True (specified by Collection.add(E)).
UnsupportedOperationException - if this list does not support the add operation.
ClassCastException - if the specified element's class prevents it from being added to this list.
NullPointerException - If the specified element is null and this list does not allow null elements.
IllegalArgumentException - If some attribute of this element prevents it from being added to this list.
void add(int index, E element)
Insert the specified element at the specified position in this list (optional operation). Moves the element currently at that position (if any) and all subsequent elements to the right (incrementing their index by one).
element - The element to insert.
UnsupportedOperationException - if the add operation is not supported
ClassCastException - if the specified element's class prevents it from being added to this list.
NullPointerException - if the specified element is null and this list does not allow null elements.
IllegalArgumentException< /strong> - if some properties of the element prevent it from being added to this list.
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size()).
The following example shows the usage of add() method- p>
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(); } } }
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)
The above is the detailed content of How to add element to list in Java?. For more information, please follow other related articles on the PHP Chinese website!