Card 05/ 08

ComparisonDifficulty: Intermediate1 min

length, length() and size(): Three Spellings for Three Types

Three ways of asking how many things are in something, and which one compiles depends entirely on what you are holding. Getting it wrong is a compile error rather than a bug, which is the one merciful thing about it.

How to ask each of the three types how many elements it has
You haveYou writeIt is
An arraydays.lengthA field on the array object
A Stringname.length()A method on String
A List, Set or Maporders.size()A method on the collection interface
java
String[] days = {"Mon", "Tue"};
String name = "Monday";
List<String> queue = List.of("a", "b", "c");

System.out.println(days.length + " " + name.length() + " " + queue.size());
text
2 6 3

There is no deep reason for the inconsistency — arrays are built into the language and predate the collections library, and String predates both. It is history, and it is not going to change.

The decision rule. If the type is written with square brackets, it is .length with no brackets after it. If it is text, it is .length(). Everything else that holds a group of things is .size().