简体   繁体   English

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

[英]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?我可以通过哪些不同的方式访问数组、集合( ListSet等)和String对象的长度? Why is it different?为什么不一样?

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 (包括CharBufferSegmentStringStringBufferStringBuilder ):使用.length()


Arrays数组

One would use the .length property on an array to access it.可以使用数组上的.length属性来访问它。 Despite an array being a dynamically created Object , the mandate for the length property is defined by the Java Language Specification, §10.3 :尽管数组是动态创建的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 .数组的长度可用作最终实例变量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.)集合( SetList等)

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 ).某些集合可能会拒绝添加元素,因为它是null ,或者它是重复的(在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<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

*: 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.顺便说一句, Map不是Collection ,但它也定义了size()方法。 This simply returns the number of key-value pairs contained in the Map .这只是返回Map包含的键值对的数量。

String

A String has a method length() defined. String定义了一个方法length() What it does is print the number of characters present in that instance of the String .它的作用是打印该String实例中存在的字符数。

Example:例子:

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

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

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. CharSequence (包括String )上的方法称为.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. Collection上的方法称为.size()因为并非每个集合都是具有开始和结束的序列。 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.你会说你的收藏的“大小”是 2,000,但你不会说你的收藏的“长度”是 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;碰巧一些像ArrayList这样的集合确实代表了一个序列,在那里讨论它们的长度是有意义的,但该方法仍然命名为.size()因为该方法名称是从Collection接口继承的; it would be strange to add another method named .length() for sequential collections, which would do the same thing as the inherited .size() .为顺序集合添加另一个名为.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 .length isn't a method.它们不是可以声明.length()方法的“数组”类的实例,因此.length不是方法。 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 .获取数组长度的表达式被编译为字节码指令arraylength The distinct bytecode instruction for an array's length corresponds with the distinct syntax for it.数组长度的不同字节码指令对应于它的不同语法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Java中的列表数组获取格式化的字符串? - How I can get formated string from List array in Java? 如何在Java中从逗号分隔的字符串中获取数组 - How can I get an array from a comma separated string in Java 如何从 linux 命令获取 java 中的字符串数组? - How can i get a string array in java from linux command? 如何从Java中的字符串数组获取固定大小数字 - How to get fix size numbers from string array in Java 如何在Java集合中转换为json响应的字符串? - how can i convert this string which is json response in java collection? 如何在Java中的复杂集合mongodb中排序并获取列表? - How can I sort and get a list in complex collection mongodb in java? How can I use Java Stream in order to iterate on a collection on object and use a specific string field of each object to create a new array? - How can I use Java Stream in order to iterate on a collection on object and use a specific string field of each object to create a new array? 如何使用 Java Stream 修复此嵌套集合代码,以便从 object 的属性创建字符串数组? - How can I fix this nested collection code using Java Stream in order to create an array of string from the property of an object? 在 java 中,如何在另一个字符串数组中搜索字符串数组? - In java, how can i search String array in another String array? 我可以用另一个集合初始化Java数组吗? - Can I initialize a Java array with another collection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM