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!
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js