What is the difference between .size()
and .length
? Is .size()
only for arraylists and .length
only for arrays?
size()
is a method specified in java.util.Collection
, which is then inherited by every data structure in the standard library. length
is a field on any array (arrays are objects, you just don't see the class normally), and length()
is a method on java.lang.String
, which is just a thin wrapper on a char[]
anyway.
Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.
.length
is a field, containing the capacity (NOT the number of elements the array contains at the moment) of arrays.
length()
is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value.
size()
is a method implemented by all members of Collection (lists, sets, stacks,...). It returns the number of elements (NOT the capacity; some collections even don´t have a defined capacity) the collection contains.I bet (no language specified) size()
method returns length
property.
However valid for
loop should looks like:
for (int i = 0; i < values.length; i++) {}
length variable:
In Java, array (not java.util.Array) is a predefined class in the language itself. To find the elements of an array, designers used length variable (length is a field member in the predefined class). They must have given length() itself to have uniformity in Java; but did not. The reason is by performance, executing length variable is speedier than calling the method length(). It is like comparing two strings with == and equals(). equals() is a method call which takes more time than executing == operator.
size() method:
It is used to find the number of elements present in collection classes. It is defined in java.util.Collection interface.
Based on the syntax I'm assuming that it is some language which is descendant of C. As per what I have seen, length
is used for simple collection items like arrays and in most cases it is a property.
size()
is a function and is used for dynamic collection objects. However for all the purposes of using, you wont find any differences in outcome using either of them. In most implementations, size simply returns length property.
length is constant which is used to find out the array storing capacity not the number of elements in the array
Example:
int[] a = new int[5]
a.length
always returns 5, which is called the capacity of an array. But
number of elements in the array is called size
Example:
int[] a = new int[5]
a[0] = 10
Here the size would be 1, but a.length
is still 5. Mind that there is no actual property or method called size
on an array so you can't just call a.size
or a.size()
to get the value 1.
The size()
method is available for collections, length
works with arrays in Java.