Card 05/ 08

ComparisonDifficulty: Intermediate1 min

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.

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().

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.