Java 简明教程
Java - Arrays
What are Arrays in Java?
Java 提供了一个称为 array 的数据结构,其中存储了相同数据类型元素的一个固定大小的顺序集合。数组用于存储数据集合,但通常将其视为相同类型的变量集合更有用。
Java provides a data structure called the array, which stores a fixed-size sequential collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
与其声明单个变量,例如 number0、number1、…、number99,您可以声明一个数组变量,例如 numbers,并使用 numbers[0]、numbers[1] 和…、 numbers[99] 表示各个变量。
Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.
本教程介绍了如何声明数组变量、创建数组以及使用索引变量处理数组。
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
Declaring Array Variables
要在程序中使用数组,您必须声明一个变量来引用数组,并且必须指定此变量可以引用的数组类型。以下是声明数组变量的语法 −
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − 首选 dataType[] arrayRefVar 样式。dataType arrayRefVar[] 样式源自 C/C 语言,Java 中采用它是为了适应 C/C 程序员。
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C language and was adopted in Java to accommodate C/C programmers.
Creating Arrays
您可以使用以下语法通过 new 运算符创建数组 −
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
以上语句执行两项操作 −
The above statement does two things −
-
It creates an array using new dataType[arraySize].
-
It assigns the reference of the newly created array to the variable arrayRefVar.
声明数组变量、创建数组,以及将数组的引用分配给变量,可以合并到一个语句中,如下所示 −
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
也可以按照如下方法创建数组:
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
数组元素是通过 index 访问的。数组索引基于 0;也就是说,它们从 0 开始到 arrayRefVar.length-1。
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example
以下语句声明了一个数组变量 myList,创建了一个由双精度类型组成的 10 个元素的数组,并将它的引用赋值给 myList:
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −
double[] myList = new double[10];
下图表示数组 myList。这里,myList 包含 10 个双精度值,索引从 0 到 9。
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
Processing Arrays
在处理数组元素时,我们经常使用 for 循环或 foreach 循环,因为数组中的所有元素都是同类型的,并且数组大小是已知的。
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Example: Creating, Iterating and Performing Other Operations on Arrays
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
这会产生以下结果 −
This will produce the following result −
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The foreach Loops with Arrays
JDK 1.5 引入了称为 foreach 循环或增强型 for 循环的新循环,它允许你在不使用索引变量的情况下按顺序遍历整个数组。
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
以下代码显示了数组 myList 中的所有元素:
The following code displays all the elements in the array myList −
Example: Displaying All Elements of an Arrays
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
这会产生以下结果 −
This will produce the following result −
1.9
2.9
3.4
3.5
Passing Arrays to Methods
就像可以将基本类型值传递给方法一样,也可以将数组传递给方法。例如,以下方法显示 int 数组中的元素:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array −
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
可以通过传递一个数组来调用它。例如,以下语句调用 printArray 方法来显示 3、1、2、6、4 和 2:
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2 −
Returning an Array from a Method
方法还可以返回一个数组。例如,以下方法返回一个数组,该数组是另一个数组的逆序:
A method may also return an array. For example, the following method returns an array that is the reversal of another array −
The Arrays Class
java.util.Arrays 类包含用于排序和搜索数组、比较数组和填充数组元素的各种静态方法。这些方法对所有基本类型都进行了重载。
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
Sr.No. |
Method & Description |
1 |
public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)). |
2 |
public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) |
3 |
public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.) |
4 |
public static void sort(Object[] a) Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.) |