How to Find Size of ArrayList in Java - Simple Guide
To find the size of an
ArrayList in Java, use the size() method. It returns the number of elements currently stored in the list as an int value.Syntax
The syntax to get the size of an ArrayList is simple:
arrayList.size()- calls thesize()method on theArrayListobject.- This method returns an
intrepresenting the number of elements in the list.
java
int size = arrayList.size();Example
This example creates an ArrayList of strings, adds some items, and prints the size using size().
java
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); int size = fruits.size(); System.out.println("Number of fruits: " + size); } }
Output
Number of fruits: 3
Common Pitfalls
Some common mistakes when finding the size of an ArrayList include:
- Using
lengthinstead ofsize().lengthis for arrays, notArrayList. - Calling
size()on anullreference causes aNullPointerException. - Expecting
size()to return capacity instead of the actual number of elements.
java
/* Wrong: Using length on ArrayList */ // int size = arrayList.length; // This causes a compile error /* Correct: Use size() method */ int size = arrayList.size();
Quick Reference
Remember these key points:
size()returns the current number of elements.- It does not return the capacity of the list.
- Always ensure the
ArrayListis notnullbefore callingsize().
Key Takeaways
Use the
size() method to get the number of elements in an ArrayList.Do not use
length with ArrayList; it is for arrays only.Calling
size() on a null ArrayList causes an error.size() returns the count of elements, not the capacity.Always check your ArrayList is initialized before calling
size().