What are the different ways that I can access the length of an array, a collection (List
, Set
, etc.), and a String
object? Why is it different?
To get the size of a Java array, you use the length property. To get the size of an ArrayList, you use the size() method.
With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.
The Size of the different collections can be found with the size() method. This method returns the number of elements in this collection. This method does not take any parameters.
For an array: use .length
.
For a Collection
(or Map
): use .size()
.
For a CharSequence
(which includes CharBuffer
, Segment
, String
, StringBuffer
, and StringBuilder
): use .length()
.
One would use the .length
property on an array to access it. Despite an array being a dynamically created Object
, the mandate for the length
property is defined by the Java Language Specification, §10.3:
An array is created by an array creation expression (§15.10) or an array initializer (§10.6).
An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable
length
.An array initializer creates an array and provides initial values for all its components.
Since the length of an array cannot change without the creation of a new array instance, repeated accesses of .length
will not change the value, regardless of what is done to the array instance (unless its reference is replaced with a differently sized array).
As an example, to get the length of a declared one-dimensional array, one would write this:
double[] testScores = new double[] {100.0, 97.3, 88.3, 79.9};
System.out.println(testScores.length); // prints 4
To get lengths in an n-dimensional array, one needs to bear in mind that they are accessing one dimension of the array at a time.
Here's an example for a two-dimensional array.
int[][] matrix
= new int[][] {
{1, 2, 3, 4},
{-1, 2, -3, 4},
{1, -2, 3, -4}
};
System.out.println(matrix.length); // prints 3 (row length or the length of the array that holds the other arrays)
System.out.println(matrix[0].length); // prints 4 (column length or the length of the array at the index 0)
This is important to make use of, especially in the case of jagged arrays; the columns or rows may not always line up all the time.
Set
, List
, etc.)For every object that implements the Collection
interface, they will have a method called size()
with which to access the overall size of the collection.
Unlike arrays, collections are not fixed length, and can have elements added or removed at any time. A call to size()
will produce a nonzero result if and only if there has been anything added to the list itself.
Example:
List<String> shoppingList = new ArrayList<>();
shoppingList.add("Eggs");
System.out.println(shoppingList.size()); // prints 1
Certain collections may refuse to add an element, either because it's null
, or it's a duplicate (in the case of a Set
). In this case, repeated additions to the collection will not cause the size to increment.
Example:
Set<String> uniqueShoppingList = new HashSet<>();
uniqueShoppingList.add("Milk");
System.out.println(uniqueShoppingList.size()); // prints 1
uniqueShoppingList.add("Milk");
System.out.println(uniqueShoppingList.size()); // prints 1
Accessing the size of a List<List<Object>>
* is done in a similar way to a jagged array:
List<List<Integer>> oddCollection = new ArrayList<>();
List<Integer> numbers = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
}};
oddCollection.add(numbers);
System.out.println(oddCollection.size()); // prints 1
System.out.println(oddCollection.get(0).size()); // prints 3
*: Collection
doesn't have the get
method defined in its interface.
As an aside, a Map
is not a Collection
, but it also has a size()
method defined. This simply returns the number of key-value pairs contained in the Map
.
String
A String
has a method length()
defined. What it does is print the number of characters present in that instance of the String
.
Example:
System.out.println("alphabet".length()); // prints 8
Don't forget CollectionUtils.size()
from the commons library, its null safe so you don't have to null check beforehand.
Why is it different?
I'll try to answer this part, since it doesn't seem to be covered in the other answers.
The method on a CharSequence
(including String
) is called .length()
because a sequence has a length. "Length" is a sensible word to use for a sequence, because it has a start and an end, and you can measure how far apart they are; just like you can measure the distance between two ends of a stick to get the "length" of the stick.
The method on a Collection
is called .size()
because not every collection is a sequence with a start and an end. Imagine having a collection of two thousand different stamps; you would say that the "size" of your collection is 2,000, but you would not say that the "length" of your collection is 2,000. The word "size" is more natural for things that aren't measured from start to end. It happens that some collections like ArrayList
do represent a sequence where it makes sense to talk about their length, but the method is still named .size()
because that method name is inherited from the Collection
interface; it would be strange to add another method named .length()
for sequential collections, which would do the same thing as the inherited .size()
.
Arrays are sequences, so they have lengths. However, arrays are a low-level feature of the language; they aren't instances of an "array" class that could declare a .length()
method, so therefore .length
isn't a method. Syntactically it looks like accessing a field, but it isn't a field; an expression which gets the length of an array is compiled to the bytecode instruction arraylength
. The distinct bytecode instruction for an array's length corresponds with the distinct syntax for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With