如何在Java中获取数组,集合或字符串的大小?

时间:2021-11-14 21:27:57

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?

有什么不同的方法可以访问数组的长度,集合(List,Set等)和String对象?为什么会有所不同?

2 个解决方案

#1


29  

Abridged:

For an array: use .length.

对于数组:使用.length。

For a Collection (or Map): use .size().

对于Collection(或Map):使用.size()。

For a CharSequence (which includes CharBuffer, Segment, String, StringBuffer, and StringBuilder): use .length().

对于CharSequence(包括CharBuffer,Segment,String,StringBuffer和StringBuilder):使用.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:

可以使用数组上的.length属性来访问它。尽管数组是动态创建的Object,但length属性的权限由Java语言规范§10.3定义:

An array is created by an array creation expression (§15.10) or an array initializer (§10.6).

数组由数组创建表达式(第15.10节)或数组初始值设定项(第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).

由于数组的长度在没有创建新数组实例的情况下无法更改,因此重复访问.length将不会更改该值,无论对数组实例执行了什么操作(除非将其引用替换为不同大小的数组)。

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.

要获得n维数组的长度,需要记住它们一次访问数组的一个维度。

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.

对于实现Collection接口的每个对象,它们都有一个名为size()的方法,用于访问集合的整体大小。

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.

与数组不同,集合的长度不固定,并且可以随时添加或删除元素。当且仅当列表本身添加了任何内容时,对size()的调用才会产生非零结果。

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.

某些集合可能拒绝添加元素,因为它是null,或者它是重复的(在Set的情况下)。在这种情况下,重复添加集合不会导致大小增加。

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

*:Collection没有在其接口中定义get方法。

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.

另外,Map不是Collection,但它也定义了size()方法。这只是返回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.

String具有定义的方法length()。它的作用是打印String实例中存在的字符数。

Example:

例:

System.out.println("alphabet".length()); // prints 8

#2


3  

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

不要忘记来自commons库的CollectionUtils.size(),它的null安全,所以你不必事先进行null检查。

#1


29  

Abridged:

For an array: use .length.

对于数组:使用.length。

For a Collection (or Map): use .size().

对于Collection(或Map):使用.size()。

For a CharSequence (which includes CharBuffer, Segment, String, StringBuffer, and StringBuilder): use .length().

对于CharSequence(包括CharBuffer,Segment,String,StringBuffer和StringBuilder):使用.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:

可以使用数组上的.length属性来访问它。尽管数组是动态创建的Object,但length属性的权限由Java语言规范§10.3定义:

An array is created by an array creation expression (§15.10) or an array initializer (§10.6).

数组由数组创建表达式(第15.10节)或数组初始值设定项(第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).

由于数组的长度在没有创建新数组实例的情况下无法更改,因此重复访问.length将不会更改该值,无论对数组实例执行了什么操作(除非将其引用替换为不同大小的数组)。

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.

要获得n维数组的长度,需要记住它们一次访问数组的一个维度。

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.

对于实现Collection接口的每个对象,它们都有一个名为size()的方法,用于访问集合的整体大小。

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.

与数组不同,集合的长度不固定,并且可以随时添加或删除元素。当且仅当列表本身添加了任何内容时,对size()的调用才会产生非零结果。

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.

某些集合可能拒绝添加元素,因为它是null,或者它是重复的(在Set的情况下)。在这种情况下,重复添加集合不会导致大小增加。

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

*:Collection没有在其接口中定义get方法。

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.

另外,Map不是Collection,但它也定义了size()方法。这只是返回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.

String具有定义的方法length()。它的作用是打印String实例中存在的字符数。

Example:

例:

System.out.println("alphabet".length()); // prints 8

#2


3  

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

不要忘记来自commons库的CollectionUtils.size(),它的null安全,所以你不必事先进行null检查。