w3resource

Java ArrayList.add(E e) Method

public boolean add(E e)

This method is used to append an element to a ArrayList.

Package: java.util

Java Platform: Java SE 8

Syntax:

add(E e)

Parameters:

Name Description
e Element to be appended to this list.

Return Value :
Returns true if the element was successfully added; false otherwise.

Return Value Type: boolean

Pictorial presentation of ArrayList.add(E e) Method

Java ArrayList.add(E e) Method

Example: ArrayList.add(E e) Method

This example creates an ArrayList object, and adds 5 colors to the list.

import java.util.*;

public class test {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<String> color_list = new ArrayList<String>(5);

    // use add() method to add values in the list
    color_list.add("White");
    color_list.add("Black");
    color_list.add("Red");
    color_list.add("White");
	color_list.add("Yellow");
	    
	// Print out the colors in the ArrayList
    for (int i = 0; i < 5; i++)
      {
         System.out.println(color_list.get(i).toString());
      }
  }
}  
 

Output:

F:\java>javac test.java

F:\java>java test
White
Black
Red
White
Yellow

Java Code Editor:

Previous:set Method
Next:add(int index, E element) Method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-tutorial/arraylist/arraylist_add-element.php