In Java in particular, on Strings
, you call string.length()
, whereas in Lists
you call list.size()
. Is there a technical difference between the two terms, seeing as a String
is really just a list of chars
?
Any comments appreciated.
In Java in particular, on Strings
, you call string.length()
, whereas in Lists
you call list.size()
. Is there a technical difference between the two terms, seeing as a String
is really just a list of chars
?
Any comments appreciated.
I don't think so. It is more likely caused by the API being work on a large team and different people have different take on what the name should be, especially with words that synonym in certain context, such as size and length in this matter.
In general, length() is used when something has a constant length, while size() is used on something with a variable length. Past that, I know of no good reason for using two nearly-synonymous terms.
As others have touched on, I think it is a semantic difference. Arrays are very clearly defined and are referred to as having length. A collection of objects is more fuzzy, partly because its implementation (is it an array, linked-list, tree?) isn't necessarily your concern. A tree doesn't really have a length, but it has a definite size, so size might make more sense semantically.
Ideally, count
would be the number of items, and size
would be the amount of storage taken up (as in sizeof
).
In practice, all three (including length
, which is the most ambiguous) are muddled up in many widely-used libraries, so there's no point trying to impose a pattern on them at this stage.
For me,
"length" implies an order, you are measuring a length from the start to the end.
"size" implies how big something is without implying an order, start or end.
To me, "size" is used when describing a structure or other way to organize bytes in a computer. It doesn't necessarily have to be instantiated. "length", on the other hand, implies how large a particular buffer of bytes in memory is at a given point.
E.g. What is the length of the buffer you're providing? It is the same number of bytes as the size of structure x.