Thursday, December 15, 2022

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 load 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 in Java [Example]




Array length vs ArrayList Size Example in Java

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){
            arrList.add(str);
        }
        int size = items.size();
        System.out.println(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.


Other Java Collections and Stream Tutorial you may like
  • How to convert List to Map in Java 8 (solution)
  • How to sort List in Java 8 and Java 11 (sorting list example)
  • 5 Free Courses to learn Java 8 and 9 (courses)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • How to use peek() method in Java 8 (example)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to sort the map by keys in Java 8? (example)
  • How to use Stream class in Java 8 (tutorial)
  • What is the default method in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • Difference between abstract class and interface in Java 8? (answer)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to use filter() method in Java 8 (tutorial)
  • How to join String in Java 8 (example)
  • 7 Best Collections and Stream Courses for Java developers (courses)

Thanks for reading this article so far. If you like this Java Listtutorial then please share it with your friends and colleagues. If you have any questions, doubts,s or feedback about this tutorial and my explanation then please drop a comment.

P. S. - If you want to learn Java Collection Framework and Stream in depth then you can also checkout this list of best Java Collections and Stream courses for both beginners and experienced Java developers. It contains tried and tested online training courses to learn Stream and Collection in depth. 
 

No comments:

Post a Comment

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