Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

Array length vs ArrayList Size in Java [Example]

One of the confusing parts in learning Java for a beginner to understand how to find the length of array and ArrayList in Java? The main reason for the confusion is an inconsistent way of calculating the length between two. Calling size() method on arrays and length, or even length() on ArrayList is a common programming error made by beginners. The main reason for the confusion is the special handling of an array in Java.  Java native arrays have built-in length attribute but no size() method while the Java library containers, known as Collection classes like ArrayList<>, Vector<>, etc,  all have a size() method. 

There is one more thing which adds to this confusion, that is capacity, at any point capacity of any collection class is the maximum number of elements collection can hold. the size of collection must be less than or equal to its capacity.

Though in reality, collection resize themselves even before it reaches its capacity, controlled by laod factor.  I have mentioned this before on my post difference between ArrayList and Array in Java, if you not read it already, you may find some useful detail there as well.

So, use length attribute to get number of elements in a array, also known as length, and for same thing in Collection classes like ArrayList, Vector, use size() method. To give you more context, consider following lines of code, can you spot the error, which is bothering our beginner friend:

Array length vs ArrayList Size

import java.util.*;
public class ArrayListTest {
    public static void main(String[] args) {
        ArrayList<String> arrList = new ArrayList<String>();
        String[] items = { "One", "Two", "Three", "Four", "Five" };
        for(String str: items){
        int size = items.size();

Array length vs ArrayList Size in JavaThis program will throw compile time error at line items.size(), because item is an array, not ArrayList, but it very easy to confuse between them, especially when you are just starting to learn Java Programming language. 

By the way you can also initialize ArrayList in one line as shown in following example :

Arrays.asList("First", "Second", "Third", "Fourth", "Fifth");

It's handy way to declare and initialize ArrayList in same place, similar to array in Java.  So next time don't confuse between length and size(), array are special object in Java and has attribute called length, which specifies number of buckets in array, while ArrayList is a Collection class, which inherit size() method, which returns number of elements inside Collection. Remember, size is different than capacity of collection. At any point, size <= capacity of collection.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.