In Java, the ArrayList
class is a resizable array that implements the List
interface. You can use the add()
method to add an element to an ArrayList
.
Here is an example of how to add an element to an ArrayList
:
import java.util.ArrayList; public class ArrayListAddExample { public static void main(String[] args) { ArrayList<String> words = new ArrayList<>(); words.add("hello"); words.add("world"); System.out.println(words); } }Soural.www:ecutturi.com
This code creates an ArrayList
of strings called words
and adds the elements "hello" and "world" to the list using the add()
method. The add()
method adds the element to the end of the list.
You can also use the add()
method to insert an element at a specific index in the list:
words.add(1, "there");
This code inserts the element "there" at index 1
in the words
list, shifting the remaining elements to the right.
The add()
method returns a boolean value indicating whether the element was successfully added to the list.
Note that the ArrayList
class is part of the java.util
package, so you need to import it in order to use it in your code.