Wednesday, November 23, 2011

To calculate length or size, why array is having a ‘length’ property while the list is having a ‘size()’ method?



int[] arrayInt = new int[] {1, 2, 3, 4, 5, 6};

O/P is: -
arrInt.length = 6

array.length is actually a public final member/field of the array, which contains the number of components of the array. It is final because arrays in java are immutable, which means once the array is defined then an array can not be grow or shrink, however the elements within the array can change. So, it means once the size of array is defined it can not be changed, that is why it is final and treated as a property/field/instance variable.

A java array is allocated with a fixed number of element slots. The "length" attribute will tell you how many. That number is immutable for the life of the array. For a resizable equivalent, you need one of the java.util.List classes - where you can use the size() method to find out how many elements are in use.

List<Integer> list = new ArrayList<Integer>(20);
list.add(1);
list.add(2);
list.add(3);

O/P is: -
list.size() = 3

java.util.List is used when you want a datastructure where you can grow/shrink your datastructure easily as per the need. In java.util.List, the field/property is kept private because java.util.List can be grow/shrink as per the need. So, the size is keeps changing on addition/removal of element from the java.util.List. So, it means java.util.List is a mutable object, and that is why the reason size is a method which returns the size of java.util.List, that is, it tells the number of item currently present in the list irrespective of its capacity.

No comments: