views:

203

answers:

6

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.

+3  A: 

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.

DJ
+6  A: 

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.

Joel Rondeau
+2  A: 

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.

Jonathon
+6  A: 

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.

Daniel Earwicker
+1 for admitting that programmers aren't perfect.
Tom R
Sometimes `size` is used for the number of items, and `capacity` is for the amount of storage taken up.
Johannes Schaub - litb
Daniel Earwicker
@Earwicker, such behavior would invalidate `.begin()` and `.end()`, i think. However you are guaranteed that they stay valid for at least `.capacity() - .size()` push-backs.
Johannes Schaub - litb
+2  A: 

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.

Peter Lawrey
A: 

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.

jdizzle