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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23730092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:54:59  来源:igfitidea点击:

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

javaarraysstringcollections

提问by Makoto

What are the different ways that I can access the length of an array, a collection (List, Set, etc.), and a Stringobject? Why is it different?

什么不同的方式,我可以访问的阵列的长度,集合(ListSet等),和一个String对象?为什么不一样?

采纳答案by Makoto

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(其包括CharBufferSegmentStringStringBuffer,和StringBuilder):使用.length()



Arrays

数组

One would use the .lengthpropertyon an array to access it. Despite an array being a dynamically created Object, the mandate for the lengthproperty 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).

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.

数组由数组创建表达式(§15.10)或数组初始值设定项(§10.6) 创建

数组创建表达式指定元素类型、嵌套数组的级别数以及至少一层嵌套的数组长度。数组的长度可用作最终实例变量length

数组初始值设定项创建一个数组并为其所有组件提供初始值。

Since the length of an array cannot change without the creation of a new array instance, repeated accesses of .lengthwill 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.)

集合(SetList等)

For every object that implements the Collectioninterface, they will have a methodcalled 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,或者是重复的(在 a 的情况下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<Object>>*的大小以类似于锯齿状数组的方式完成:

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

*: Collectiondoesn't have the getmethod defined in its interface.

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

As an aside, a Mapis not a Collection, but it also has a size()method defined. This simply returns the number of key-value pairs contained in the Map.

顺便说一句, aMap不是 a Collection,但它也size()定义了一个方法。这只是返回包含在Map.

String

String

A Stringhas a method length()defined. What it does is print the number of characters present in that instance of the String.

A定义String了一个方法length()。它的作用是打印该String.

Example:

例子:

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

回答by Jimmy

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

不要忘记CollectionUtils.size()公共库中,它的空值安全,因此您不必事先进行空值检查。

回答by kaya3

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.

调用a CharSequence(包括String)上的方法是.length()因为序列有长度。“长度”是一个用于序列的合理词,因为它有开始和结束,你可以测量它们相距多远;就像你可以测量一根棍子两端之间的距离来得到棍子的“长度”。

The method on a Collectionis 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 ArrayListdorepresent 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 Collectioninterface; it would be strange to add anothermethod named .length()for sequential collections, which would do the same thing as the inherited .size().

Collection调用a 上的方法是.size()因为并非每个集合都是具有开始和结束的序列。想象一下有两千种不同的邮票;你会说你的收藏的“大小”是 2,000,但你不会说你的收藏的“长度”是 2,000。对于从头到尾都没有测量过的事物,“大小”这个词更自然。碰巧一些像ArrayList这样的集合确实代表了一个序列,在那里谈论它们的长度是有意义的,但是该方法仍然被命名,.size()因为该方法名称是从Collection接口继承的;添加另一个.length()顺序集合命名的方法会很奇怪,.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 .lengthisn'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 instructionarraylength. The distinct bytecode instruction for an array's length corresponds with the distinct syntax for it.

数组是序列,所以它们有长度。然而,数组是该语言的一个低级特性;它们不是可以声明.length()方法的“数组”类的实例,因此.length不是方法。从语法上看,它看起来像访问一个字段,但它不是一个字段;获取数组长度的表达式被编译为字节码指令arraylength。数组长度的不同字节码指令对应于它的不同语法。