Adding Elements to an ArrayList in Java


In Java, ArrayList is a resizable array, which can also be defined as a sequential order of elements. Unlike simple arrays, Java ArrayLists are more flexible and can contain many data types. This article shows you how to use this feature.

The Java ArrayList class uses a dynamic array to store its elements. It is similar to an array but has no size limit. We can add or remove items at any time. This makes them much more flexible than traditional arrays.

Element can be added in Java ArrayList using add() method of java.util.ArrayList class.

The element passed as a parameter gets inserted at the end of the list.

Method Declaration:

public boolean add(Object element)

The element specified in parameter will get added to the end of the list and this method returns a boolean value true.

Adding elements to ArrayList Sample Java Program:

import java.util.ArrayList; public class Main{ public static void main(String[] args) { // create Array List ArrayList<String> city =new ArrayList<String>(); city.add("chennai"); city.add("Hyderabad"); city.add("Vizag"); city.add("Mumbai"); System.out.println(city); } }


[chennai, Hyderabad, Vizag, Mumbai]

Want to Clear Java Interview? Read Java Interview Notes prepared by Us

Are You Good enough in Java? Prove it!


Get Answers to your Programming Questions

Recommended Deals ends in

Quiz For You:

Search Tags