How to get the length of an ArrayList in Java

Updated onbyAlan Morel
How to get the length of an ArrayList in Java

ArrayList in Java are, as the name implies, a combination of an array and a list.

It acts like an array because that is how it is stored in memory, but it also acts like a list because it can be dynamically allocated and resized.

One of the most important things you'll need to know is how to get the size of your ArrayList, because it can change over time as your program runs.

In this post, we'll learn how to get the size of an ArrayList in Java.

Initializing an ArrayList

Let's first start off with an example ArrayList.

We can initialize an ArrayList by using the built-in asList() method.

This method takes a list of elements as its arguments, and returns to you an initialized ArrayList.

JAVA
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

Make sure to import the ArrayList class from the java.util package.

JAVA
import java.util.ArrayList;

Now that we have an ArrayList, let's move on to getting the size of it.

Getting the Size of an ArrayList

Once you have your ArrayList, the best way to get the size of it is to use the built-in size() method from the ArrayList class.

This method will return to you the total number of elements that exist in the ArrayList.

JAVA
int size = list.size();

Here's a full example:

JAVA
import java.util.Arrays; import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); int size = list.size(); System.out.println(size); } }
BASH
5

Conclusion

In this post, we learned how to initialize an ArrayList and then how to get the size of it.

Just use the size() method to get the size of your ArrayList and you're good to go.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.