In this tutorial, you will learn the difference between length of Array and size of ArrayList in Java..
Length of Array:
// creating an array arr[] to hold 25 elements String arr[] = new String[25];
To find the number of elements in an array, we use length property. This is how we find number of elements in an array:
//This statement will print 25 as the size of array arr is 25 System.out.println(arr.length);
Size of ArrayList:
ArrayList doesn’t have length property. To find the size of ArrayList, we use size() method.
// Creating an ArrayList of String type ArrayList fruits = new ArrayList(); // adding elements to ArrayList fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); fruits.add("Grapes");
This is how, you can print the size of ArrayList.
// This statement will print 4 as arraylist has 4 elements System.out.println(fruits.size());
Example to demonstrate the length of Array and size of ArrayList in Java
In the following example, we have created an array and added four elements to it. We have also created an ArrayList and added three elements to it. We are printing the size of array using length
property and size of ArrayList using size()
method.
The important point to note is: If an array is defined with size 10 like this
String arr[] = new String[10];
but we are only adding four elements. The length property for this array would return 10 even though it has only four elements.
import java.util.ArrayList; public class JavaExample { public static void main(String[] args) { //Creating an array to hold 4 elements String arr[] = new String[4]; //Storing 4 elements to array arr arr[0] = "Hello"; arr[1] = "Hi"; arr[2] = "Bye"; arr[3] = "See, ya!"; //print size of arr System.out.println("Size of array: "+arr.length); // Creating an ArrayList ArrayList<String> names = new ArrayList<String>(); //Adding elements names.add("Chaitanya"); names.add("Steve"); names.add("Rahul"); // print size of ArrayList System.out.println("Size of ArrayList: "+names.size()); } }
Output:
Size of array: 4 Size of ArrayList: 3