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.
Answer from MattPutnam on Stack Overflowsize() 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 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.
[Java] size vs. length
x.length, x.length(), or length(x)?
Why is getting the length of an array O(1) and not O(n)?
Kotlin collections - Difference between size and count()?
From "Kotlin in Action" book:
SIDEBAR
"Using the right function for the job: count vs. size
It’s extremely easy to forget about count and implement it by filtering the collection and getting its size:
println(people.filter(canBeInClub27).size)
1
But in this case, an intermediate collection is created to store all the elements that satisfy the predicate. On the other hand, the count method only tracks the number of matching elements, not the elements themselves, and is therefore more efficient. As a general rule, try to find the most appropriate operation that satisfies your needs."
More on reddit.comWhat is the reasoning behind why some objects use size() and some use length(). Why don't they all use one or the other?