Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...