Understanding ArrayList in Java
The below article goes through explaining ArrayList in Java with suitable examples. It covers the creation and operations on ArrayList along with a few methods in it. Let’s begin!
Contents
- What is ArrayList in Java?
- How to create an ArrayList in Java?
- Operations on ArrayList
- Methods of ArrayList Class
- Iterate through an ArrayList
Compare best Courses on Java Programming from Coursera, Udemy, and Udacity.
Best-suited Java courses for you
Learn Java with these high-rated online courses
What is ArrayList in Java?
Read: Implementing Array in Java.
ArrayList is a class that implements the List interface inside the collection framework in Java.
For more, Read: OOPs Concepts in Java.
Array Vs. ArrayList in Java
Array | ArrayList |
Static | Dynamic |
Fixed-size array | Resizable array |
It can be represented in Single dimensions or multiple dimensions. | Represented in Single dimension only. |
An array uses the length attribute to calculate the total size of the array. | An ArrayList uses the size() method to calculate the total size of the ArrayList. |
Faster speed because of fixed size. | Comparatively slower because of its dynamic nature. |
An array can contain both primitives and objects. | ArrayList cannot store primitives; it can only store objects. However, since Java 5, primitives are automatically converted into objects using autoboxing. |
Also, Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained
How to create an ArrayList in Java?
Before creating and using ArrayList, we have to import the Java.util.ArrayList package.
Syntax:
ArrayList<Type> arrayList= new ArrayList<>();
Example:
// create Integer(Wrapper class) type arraylist.ArrayList<Integer> arrayList = new ArrayList<>();// create String type arraylist.ArrayList<String> arrayList = new ArrayList<>();
Here, we have used the Integer Wrapper Class in Java to create an object of type integer. As ArrayList can’t use primitive datatype without converting it into objects.
Let’s take an example to see its implementation:
import java.util.ArrayList; class Main { public static void main(String[] args){ // create an Empty ArrayList ArrayList<String> Shapes = new ArrayList<>(); System.out.println("ArrayList: " +Shapes); }}
Explanation:
In the above code we created an empty ArrayList named Shapes.
Output:
For more information: Method Overloading in Java
Operations on ArrayList
Following are some of the Operations on ArrayList–
Add elements
Let’s take an example to see the adding of elements in ArrayList.
Example:
import java.util.ArrayList; class Main { public static void main(String[] args){ // create an ArrayList ArrayList<String> Shapes = new ArrayList<>(); // Add elements to ArrayList Shapes.add("Rectangle"); Shapes.add("Circle"); Shapes.add("Triangle"); Shapes.add("Square"); System.out.println("ArrayList: " +Shapes); }}
Explanation:
In the above code, we created an ArrayList named Shapes and added the elements using add() method. Hence, it displays an ArrayList with elements added.
Output:
For more information: Method Overriding in Java
Access elements
Using the get() method with the argument as an index number, we can fetch or access the element at a desired position from the selected ArrayList.
Example:
import java.util.ArrayList; class Main { public static void main(String[] args){ // create an ArrayList ArrayList<String> Shapes = new ArrayList<>(); // Add elements to ArrayList Shapes.add("Rectangle"); Shapes.add("Circle"); Shapes.add("Triangle"); Shapes.add("Square"); System.out.println("ArrayList: " +Shapes); // get the element at postion 2 from the arraylist String str = Shapes.get(1); System.out.print("Element at 2nd position: " + str); }}
Explanation:
Here, we used Shapes.get(1) to fetch the element at index number one from Shapes ArrayList.
Output:
Read: Loops in Java
Change elements
In order to change the elements in the ArrayList, we use the set() method with parameters such as index number and new element.
Example:
import java.util.ArrayList; class Main { public static void main(String[] args){ // create an ArrayList ArrayList<String> Shapes = new ArrayList<>(); // Add elements to ArrayList Shapes.add("Rectangle"); Shapes.add("Circle"); Shapes.add("Triangle"); Shapes.add("Square"); System.out.println("ArrayList: " +Shapes); // Alter the element of the array list Shapes.set(2, "Hexagon"); System.out.println("Modified ArrayList: " +Shapes); }}
Explanation:
We used the set() method in the above code to alter the element at index 2 from Triangle to Hexagon.
Output:
Also, read: Strings in Java
Remove elements
We use the remove() method to delete the element whose index number is specified in the parameter of the method.
Example:
import java.util.ArrayList; class Main { public static void main(String[] args){ // create an ArrayList ArrayList<String> Shapes = new ArrayList<>(); // Add elements to ArrayList Shapes.add("Rectangle"); Shapes.add("Circle"); Shapes.add("Triangle"); Shapes.add("Square"); System.out.println("ArrayList: " +Shapes); // remove element from index 2 String str = Shapes.remove(2); System.out.println("Updated ArrayList: " +Shapes); System.out.println("Removed Element: " + str); }}
Explanation:
In the above code, we used the remove() method to delete the element at a specified index number.
Output:
Read: Access Modifiers in Java
Methods of ArrayList Class
Following are a few commonly used methods in the ArrayList class:
Methods | Descriptions |
size() | It returns the length of the ArrayList. |
sort() | It sorts the ArrayList elements. |
clone() | Creates another ArrayList with the same element, size, and capacity. |
contains() | Searches the ArrayList for the specified element and returns a boolean result. |
ensureCapacity() | Specifies the total number of the element the ArrayList can take. Hence, it sets the size of an ArrayList with the specified capacity. |
isEmpty() | Checks if the arraylist is empty or not. |
indexOf() | It searches a specified (entered) element in an ArrayList and returns the element’s index. |
clear() | Removes all the elements from the ArrayList. |
Let’s see an example to visit the implementation of the above methods.
Example:
import java.util.ArrayList;import java.util.Comparator; class Main { public static void main(String[] args){ // create an ArrayList ArrayList<String> Shapes = new ArrayList<>(); // Add elements to ArrayList Shapes.add("Rectangle"); Shapes.add("Circle"); Shapes.add("Triangle"); Shapes.add("Square"); System.out.println("ArrayList: " +Shapes); // Size of the ArrayList System.out.println("Size of the ArrayList: " +Shapes.size()); // Sorted ArrayList Shapes.sort(Comparator.naturalOrder()); System.out.println("Sorted Ascending ArrayList: " +Shapes); Shapes.sort(Comparator.reverseOrder()); System.out.println("Sorted Reverse ArrayList: " +Shapes); // create copy of ArrayList Shapes ArrayList<Integer> cloneShapes = (ArrayList<Integer>)Shapes.clone(); System.out.println("Cloned ArrayList: " + cloneShapes); // checks if circle is present in the arraylist System.out.print("Is Circle present in the arraylist: "); System.out.println(Shapes.contains("Circle")); // set the capacity of the arraylist Shapes.ensureCapacity(10); // checks if the ArrayList is empty boolean result = Shapes.isEmpty(); // false System.out.println("Is the ArrayList Shapes empty? " + result); // find the position of Square int pos = Shapes.indexOf("Square"); System.out.println("Index of element Square: " + pos); //clear the cloneShapes ArrayList cloneShapes.clear(); }}
Output:
Also Read: Difference between JDK, JRE, and JVM
Iterate through an ArrayList
We can iterate through the ArrayList using for-each loop.
Example:
import java.util.ArrayList; class Main { public static void main(String[] args){ // create an ArrayList ArrayList<String> Shapes = new ArrayList<>(); // Add elements to ArrayList Shapes.add("Rectangle"); Shapes.add("Circle"); Shapes.add("Triangle"); Shapes.add("Square"); System.out.println("ArrayList: " +Shapes); // iterate the ArrayList using for-each loop System.out.println("Accessing individual elements in Shapes ArrayList: "); for (String sh : Shapes) { System.out.println(sh); } }}
Output:
Conclusion
I hope the above article helped you build a concrete understanding of ArrayList in Java. You can read more topics to gain knowledge of concepts related to Java.
For more, Read: 8 Most Important Data Structures a Programmer Must Know
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio