In this example we are going to learn how to obtain the size of an ArrayList
object. As you might already know, a java.util.ArrayList
is a class that we can use to create a dynamic sized array. We can add and remove elements from the ArrayList
dynamically.
Because its elements can be added or removed at anytime, we might want to know the number of elements currently stored in this list. To obtain the size we can use the size()
method. This method returns an int
value that tells us the number of elements stored in the ArrayList
object.
When the list contains more than Integer.MAX_VALUE
elements this method returns Integer.MAX_VALUE
.
package org.kodejava.util;
import java.util.ArrayList;
import java.util.List;
public class ArrayListSize {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
int size = list.size();
System.out.println("List size = " + size);
}
}
In the code snippet above we start creating an instance of ArrayList
that can holds String
values. As a good practice we should always use the interface as the type of the declared object, in this case we use the List
interface. The <>
is a diamond operator, started from JDK 7 you can use this operator so that you don’t need to repeat the generic type twice between the declaration and instantiation.
After we create the ArrayList
object and add string elements to the list object, we get the size of the list by calling the size()
method. We store the result in the size
variable and print out its value. If you compile and run the code above you will get the following output:
List size = 3
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024