DEV Community

Jack Pritom Soren
Jack Pritom Soren

Posted on

3 1

ArrayList (Java Collections)

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++. The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally.

Java ArrayList Example :

Example 1 :

import java.util.*;

public class Array_List {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>(); // Creating arrayList

        list.add("James"); // adding object in arrayList
        list.add("John");

        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i)); // printing arrayList
        }

    }
}

//OutPut:
  James
  John

Enter fullscreen mode Exit fullscreen mode

Example 2:

import java.util.*;

public class Array_List {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>(); // Creating arrayList

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the Lenght: ");
        int number = scanner.nextInt();
        scanner.nextLine();

        for (int i = 1; i <= number; i++) {
            list.add(scanner.nextLine());
        }

        System.out.println(list);

    }
}

Enter fullscreen mode Exit fullscreen mode

We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases. For example:

ArrayList<int> al = ArrayList<int>(); // does not work  
ArrayList<Integer> al = new ArrayList<Integer>(); // works fine  
Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay