DEV Community 👩‍💻👨‍💻

Jack Pritom Soren
Jack Pritom Soren

Posted on

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

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.