One of the confusing part in learning Java for a beginner to understand how to find length of array and ArrayList in Java? Main reason for confusion is inconsistent way of calculating length between two. Calling
size() method on arrays and length, or even
length() on ArrayList is common programming error made by beginners. Main reason of confusion is special handling of
array in Java. Java native arrays has built-in length attribute but no
size() method while the Java library containers, known as Collection classes e.g.
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. 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 e.g.
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: