ArrayList

ArrayList

ArrayList is a class in Java that implements the List interface of the Java Collections Framework. It is a dynamic array that can grow and shrink in size as required. ArrayList allows the storage of elements of any type, including primitive types and objects.

Some important features of ArrayList are:

It is an ordered collection of elements, which means that the elements are stored in the same order in which they are added to the list.

It allows the storage of duplicate elements.

It allows random access to elements based on their index, which means that any element in the list can be accessed in constant time O(1).

It can dynamically increase or decrease its size as required.

It provides several methods to add, remove, search, and sort elements in the list.

Here is an example of how to create an ArrayList and add elements to it:

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<String>();

        names.add(“Alice”);

        names.add(“Bob”);

        names.add(“Charlie”);

        System.out.println(“Size of the ArrayList: ” + names.size());

        System.out.println(“Element at index 1: ” + names.get(1));

        for (String name : names) {

            System.out.println(name);

        }

    }

}

Output:

Size of the ArrayList: 3

Element at index 1: Bob

Alice

Bob

Charlie In this example, we create an ArrayList called names that can store String elements. We add three names to the list using the add() method. We then print the size of the list using the size() method and the element at index 1 using the get() method. Finally, we iterate over the elements in the list using a for loop and print each name.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Share this post
[social_warfare]
Vectors
Maps

Get industry recognized certification – Contact us

keyboard_arrow_up