How do I insert elements in a Java list?

JavaObject Oriented ProgrammingProgramming

<h2>Solution</h2><p>We can insert element to an array list easily using its add() method.</p><h3>Syntax</h3><pre class="result notranslate">boolean add(E e)</pre><p>Appends the specified element to the end of this list.</p><h2>Type Parameter</h2><ul class="list"><li><p><strong>E&nbsp;</strong> &minus; The runtime type of the element to be added.</p></li></ul><h3>Parameters</h3><ul class="list"><li><p><strong>e&nbsp;</strong> &minus; Element to be appended to this list</p></li></ul><h3>Returns</h3><p>It returns true.</p><h3>Throws</h3><ul class="list"><li><p><strong>UnsupportedOperationException&nbsp;</strong>&minus; If the add operation is not supported by this list</p></li><li><p><strong>ClassCastException</strong> &minus; If the class of the specified element prevents it from being added to this list.</p></li><li><p><strong>NullPointerException</strong> &minus; If the specified element is null and this list does not permit null elements.</p></li><li><p><strong>IllegalArgumentException</strong> &minus; If some property of this element prevents it from being added to this list.</p></li></ul><h2>Example</h2><p>The following example shows how to insert elements to the list using add() method.</p><pre class="demo-code notranslate language-java" data-lang="java">package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo { &nbsp; &nbsp;public static void main(String[] args) { // Create a list object &nbsp; &nbsp; &nbsp; List&lt;String&gt; list = new ArrayList&lt;&gt;(); &nbsp; &nbsp; &nbsp; // add elements to the list &nbsp; &nbsp; &nbsp; list.add(&quot;A&quot;); &nbsp; &nbsp; &nbsp; list.add(&quot;B&quot;); &nbsp; &nbsp; &nbsp; list.add(&quot;C&quot;); &nbsp; &nbsp; &nbsp; // print the list &nbsp; &nbsp; &nbsp; System.out.println(list); &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following result &minus;</p><pre class="result notranslate">[A, B, C]</pre>
Updated on 09-May-2022 11:21:29