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 TypeScript
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor
- How To Create a Modal Popup Box with CSS and JavaScript