Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the size of an array, a Collection, or a String in Java?

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?

like image 656
Makoto Avatar asked May 19 '14 05:05

Makoto


People also ask

How do you get the size of an array in Java?

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.

How do you find the size of an array of strings?

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.

How do I find the size of a collection?

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.


3 Answers

Abridged:

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


Arrays

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.

Collections (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
like image 57
Makoto Avatar answered Oct 09 '22 01:10

Makoto


Don't forget CollectionUtils.size() from the commons library, its null safe so you don't have to null check beforehand.

like image 44
Jimmy Avatar answered Oct 09 '22 01:10

Jimmy


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.

like image 36
kaya3 Avatar answered Oct 09 '22 02:10

kaya3