gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:43:23 26 4
gpt4 key购买 nike

访问数组、集合(ListSet 等)和String< 的长度有哪些不同的方法?/ 对象?为什么不一样?

最佳答案

删节:

对于数组:使用 .length .

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

对于 CharSequence (包括 CharBufferSegmentStringStringBufferStringBuilder ):使用 .length() .


数组

人们会使用 .length数组上的属性 来访问它。尽管数组是动态创建的 Object , 任务为 length属性由 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.

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

例如,要获取声明的一维数组的长度,可以这样写:

double[] testScores = new double[] {100.0, 97.3, 88.3, 79.9};
System.out.println(testScores.length); // prints 4

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

这是一个二维数组的例子。

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)

这很重要,尤其是在 jagged arrays 的情况下;列或行可能不会始终对齐。

集合( SetList 等)

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

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

例子:

List<String> shoppingList = new ArrayList<>();
shoppingList.add("Eggs");
System.out.println(shoppingList.size()); // prints 1

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

例子:

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

访问 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没有 get在其接口(interface)中定义的方法。

顺便说一句,Map不是 Collection , 但它也有一个 size() 方法定义。这只是返回 Map 中包含的键值对的数量。 .

String

A String有一个方法 length() 定义。它所做的是打印 String 的那个实例中存在的字符数。 .

例子:

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

关于java - 在 Java 中如何获取数组、集合或字符串的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23730092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com