Method .size() vs property .length in Java

Is good to know the differences of the method size() and the property of vectors .lenght in Java. Is common seeing about this in introductory disciplines about programming in College exams questions for example.

The size method is disponible in the interface Collections according your definition:

Returns the number of elements in this collection. If this collection contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
the number of elements in this collection
int size();

The length property is not a method that return something but a property disponible in a Java Array(that is a Java Object), this property holds the quantity of objects in the vector.

Remembering that a Java Array have fixed size, the variable name just point to a memory, to change this you need reallocate memory using the keyword new as the final example bellow:

 public static void main(String[] args) {
    Integer[] numbersArray = {1, 2, 3};
    numbersArray = new Integer[] {1, 2, 3, 4, 5};
    List<Integer> numberList = new ArrayList<>();
    System.out.println("Size of array: "+  numbersArray.length); // Size of array: 5
    System.out.println("Size of list: "+ numberList.size());     // Size of list: 1

Leave a Reply

Your email address will not be published. Required fields are marked *