Card 05/ 08
length vs length() vs size()
Three ways to ask how many, and which one compiles depends on what you are holding.
Arrays, strings and collections each report how many elements they hold in a different way: an array has a length field, a String has a length() method, and a collection such as a List has a size() method. Using the wrong one is a compile error rather than a bug.
| 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().
Arrays of objects follow the same rule: String[] names is still names.length, even though each element is a String with its own length() method. The brackets on the type are what decide.
← → move through sections and cards