How to get the length of an ArrayList in Java
Table of Contents
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.
JAVAArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Make sure to import the ArrayList
class from the java.util
package.
JAVAimport 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.
JAVAint size = list.size();
Here's a full example:
JAVAimport 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);
}
}
BASH5
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!
- Getting Started with Solid
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API