Basic example of array List in java

7/29/2021
All Articles

Introduction to ArrayList in Java

Basic example of array List in java

Basic example of array List in java 

The ArrayList class is a resizable array, which can be found in the java.util package.
 ArrayList is implementation of the List interface. It implements all optional list operations, and permits all elements, including null.

Introduction to ArrayList in Java

The ArrayList class in Java is a resizable array implementation of the List interface. Unlike arrays, which have a fixed size, ArrayLists can dynamically grow and shrink as elements are added or removed.

Key Properties of ArrayList:

  • Resizable Array: Implements the List interface and dynamically adjusts its size.
  • Mutable: Elements can be added and removed freely.
  • Not Thread-Safe: ArrayList is not synchronized, making it unsuitable for concurrent access.

How to Create an ArrayList in Java?

To use an ArrayList, import the java.util.ArrayList package and create an instance of ArrayList.

Example: Creating and Iterating an ArrayList

Let's see a basic example where we create an ArrayList called FriendsList, take user input via command-line, and then print the total number of elements in the list.

Java Code Example:

import java.util.*;
class FriendsList {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        ArrayList<String> myfriends = new ArrayList<>();

        System.out.println("Enter names of persons and type 'quit' to stop:");
        
        while (true) {
            String str = kb.next();
            if (str.equalsIgnoreCase("quit"))
                break;
            myfriends.add(str);
        }

        // Iterating through the ArrayList and printing each element
        for (String name : myfriends)
            System.out.println(name);
    }
}

Output Example:

Enter names of persons and type 'quit' to stop:
John
Alice
David
quit
John
Alice
David

Conclusion

In this article, we learned how to create an ArrayList in Java, add elements dynamically, and iterate through the list to print its elements.

Using ArrayList allows for flexible and efficient storage of elements, making it an essential part of Java programming.

For more Java tutorials, follow us on Instagram and Facebook!

Article