Card 05/ 08
All 8 cards
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.
| You have | You write | It is |
|---|---|---|
| An array | days.length | A field on the array object |
A String | name.length() | A method on String |
A List, Set or Map | orders.size() | A method on the collection interface |
String[] days = {"Mon", "Tue"};
String name = "Monday";
List<String> queue = List.of("a", "b", "c");
System.out.println(days.length + " " + name.length() + " " + queue.size());2 6 3There 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().