Steffe Wilson wrote:Is there any rationale to these apparent inconsistencies that will help me to remember when to use length, length() or size()? Or do I just have to remember which to use on a case-by-case basis?
First of all, the more you'll practice writing code snippets, the more you'll be used to these differences and after some time you'll remember them without any effort. And in the end you'll even know what to use without having to think about it
Let's start with String and StringBuilder: both respresent a sequence of characters; the first one is immutable, the latter is mutable. For these two it's all about words. And with words it makes (at least for me) more sense to talk about "the length of a word" than "the size of a word". Furthermore, the length (character count) should be accessible for the whole
Java Universe, but should be changed only from inside the class. There's no reason someone should be able to change it directly, the length of a
word (string) changes if characters are removed and/or added. So if you would have a public length property, you could also change the length of a string directly. So assume you have a StringBuilder with
"Java" as value. What would happen if the length was set to 2? Should the value be truncated to
"Ja"? Or what if the length was set to 10? Should the value be padded with spaces? That's why good encapsulation matters. Therefore you'll have a (read-only) method to get the character count: the
length() method.
Now let's look at ArrayList and all other collections. An ArrayList IS-A Collection. And with collections, it makes again more sense to talk about "the size of a collection" than "the length of a collection". And again, the size (number of elements) should be accessible for the whole Java Universe, but should be changed only from inside the class. Otherwise you'll face similar issues as with String and StringBuilder: if you have an ArrayList with 5 Integers and you could change the size directly to 2 or to 10, what should happen? Therefore you'll have a (read-only) method to get the number of elements in a collection: the
size() method.
Last but not least, let's have a look at the array. Arrays are special objects in Java, so each array IS-A Object! They have a simple attribute named
length which is
public and
final. Meaning the property is exposed to the whole world (
public), but it's impossible to change and thus read-only (
final). There is no "class definition" of an array (you can't find it in any
.class file), they're a part of the language itself.
Here you'll find the
Arrays section in the JLS.
Hope it helps!
Kind regards,
Roel