Basic example of array List in java
Introduction to ArrayList 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.
To use an ArrayList, import the java.util.ArrayList
package and create an instance of 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.
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);
}
}
Enter names of persons and type 'quit' to stop:
John
Alice
David
quit
John
Alice
David
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!