Java ArrayList length example shows how to get the length of the ArrayList. The example also shows how to get size or length of an ArrayList using the size method.
How to get ArrayList length in Java (ArrayList size)?
To get the length of the ArrayList, use the size
method of ArrayList.
1 |
public int size() |
This method returns number of elements in the ArrayList. It returns 0 if the ArrayList is empty.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.javacodeexamples.collections.arraylist; import java.util.ArrayList; public class ArrayListLengthExample { public static void main(String[] args) { //create new ArrayList object ArrayList<String> aListNames = new ArrayList<String>(); /* * Use size method of ArrayList * to get length of the ArrayList */ System.out.println( "ArrayList length: " + aListNames.size() ); System.out.println("Adding 2 elements to ArrayList"); //add some elements aListNames.add("Julia"); aListNames.add("Max"); //this should return 2, as we added 2 elements to ArrayList System.out.println( "ArrayList length: " + aListNames.size() ); } } |
Output
1 2 3 |
ArrayList length: 0 Adding 2 elements to ArrayList ArrayList length: 2 |
You can use the size
method to get the number of elements contained in the ArrayList and loop through them as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.javacodeexamples.collections.arraylist; import java.util.ArrayList; public class ArrayListLengthExample { public static void main(String[] args) { //create new ArrayList object ArrayList<String> aListNames = new ArrayList<String>(); //add some elements aListNames.add("Julia"); aListNames.add("Max"); System.out.println("ArrayList contains: "); for(int i=0; i < aListNames.size(); i++) System.out.println( aListNames.get(i) ); } } |
Output
1 2 3 |
ArrayList contains: Julia Max |
This example is a part of the Java ArrayList tutorial.
Please let us know your views in the comments section below.