What is the difference between .size()
and .length
? Is .size()
only for arraylists and .length
only for arrays?
Difference between length of array and size() of ArrayList in Java. ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects available in the collection. Array has length property which provides the length or capacity of the Array.
ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects available in the collection. Array has length property which provides the length or capacity of the Array. It is the total space allocated during the initialization of the array.
The size() function is consistent with other STL containers (like vector, map, etc.) and length() is consistent with most peoples intuitive notion of character strings like a word, sentence or paragraph. We say a paragraph'ss length not its size, so length() is to make things more readable.
length() : length() method is a final variable which is applicable for string objects. The length() method returns the number of characters present in the string. 1. The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With