Arrays are one of the important data structures for every programming language. Of course, different languages implement and process arrays differently.
Arrays provided in the Java language are used to store fixed-size elements of the same type.
You can declare an array variable, such as numbers[100] instead of directly declaring 100 independent variables number0, number1, ...., number99.
This tutorial will introduce you to the declaration, creation and initialization of Java arrays, and give you the corresponding code.
Array variables must first be declared before an array can be used in a program. The following is the syntax for declaring array variables:
dataType[]arrayRefVar;//首选的方法或dataTypearrayRefVar[];//效果相同,但不是首选方法
Note: It is recommended to use the dataType[] arrayRefVar declaration style to declare array variables. The dataType arrayRefVar[] style comes from the C/C++ language and is adopted in Java to allow C/C++ programmers to quickly understand the java language.
Here are code examples for both syntaxes:
double[]myList;//首选的方法或doublemyList[];//效果相同,但不是首选方法
The Java language uses the new operator to create an array. The syntax is as follows:
arrayRefVar=newdataType[arraySize];
The above syntax statement does two things:
1. Create an array using dataType[arraySize].
2. Assign the reference of the newly created array to the variable arrayRefVar.
The declaration of array variables and creation of the array can be completed in one statement, as shown below:
dataType[]arrayRefVar=newdataType[arraySize];
In addition, you can also create an array using the following method.
dataType[]arrayRefVar={value0,value1,...,valuek};
The elements of an array are accessed by index. Array indexing starts at 0, so index values range from 0 to arrayRefVar.length-1.
Then when the array opens up space, you can operate in the following way:
Example: Define an int array
public class ArrayDemo { public static void main(String args[]) { int data[] = new int[3]; /*开辟了一个长度为3的数组*/ data[0] = 10; // 第一个元素 data[1] = 20; // 第二个元素 data[2] = 30; // 第三个元素 for(int x = 0; x < data.length; x++) { System.out.println(data[x]); //通过循环控制索引 } } }
In addition to declaring and allocating space, the array itself has another allocation mode.
Example: Use step-by-step mode to open up array space
public class ArrayDemo { public static void main(String args[]) { int data[] = null; data = new int[3]; /*开辟了一个长度为3的数组*/ data[0] = 10; // 第一个元素 data[1] = 20; // 第二个元素 data[2] = 30; // 第三个元素 for(int x = 0; x < data.length; x++) { System.out.println(data[x]); //通过循环控制索引 } } }
But be sure to remember that arrays are reference data types, so space must be allocated (instantiated) before the array is used. If an array without allocated space is used, a NullPointerException
message will definitely appear:
public class ArrayDemo { public static void main(String args[]) { int data[] = null; System.out.println(data[x]); } }
This principle is exactly the same as what was explained before.
Arrays will definitely be used during development, but operations like the above are rare. In future actual development, the array concept will be used more, and when used directly, in most cases it is just a for loop output.
The element type of the array and the size of the array are determined, so when processing array elements, we usually use a basic loop or a foreach loop.
This example fully demonstrates how to create, initialize and manipulate arrays:
publicclassTestArray{ publicstaticvoidmain(String[]args){ double[]myList={1.9,2.9,3.4,3.5}; //打印所有数组元素for(inti=0;i<myList.length;i++){ System.out.println(myList[i]+""); } //计算所有元素的总和doubletotal=0; for(inti=0;i<myList.length;i++){ total+=myList[i]; } System.out.println("Totalis"+total); //查找最大元素doublemax=myList[0]; for(inti=1;i<myList.length;i++){ if(myList[i]>max)max=myList[i]; } System.out.println("Maxis"+max); } }
The compilation and running results of the above example are as follows:
1.9 2.9 3.4 3.5 Totalis11.7 Maxis3.5
JDK 1.5 introduced a new type of loop, called a foreach loop or enhanced loop, which iterates over an array without using subscripts.
The syntax format is as follows:
for(type element: array){ System.out.println(element); }
This example is used to display all elements in the array myList:
publicclassTestArray{ publicstaticvoidmain(String[]args){ double[]myList={1.9,2.9,3.4,3.5}; //打印所有数组元素for(doubleelement:myList){ System.out.println(element); } } }
The compilation and running results of the above example are as follows:
1.9 2.9 3.4 3.5
Arrays can be passed as parameters to methods. For example, the following example is a method that prints the elements in an int array.
publicstaticvoidprintArray(int[]array){ for(inti=0;i<array.length;i++){ System.out.print(array[i]+""); } }
The following example calls the printArray method to print out 3, 1, 2, 6, 4 and 2:
printArray(newint[]{3,1,2,6,4,2});
publicstaticint[]reverse(int[]list){ int[]result=newint[list.length]; for(inti=0,j=result.length-1;i<list.length;i++,j--){ result[j]=list[i]; } returnresult; }
In the above example, the result array is used as the return value of the function.
The java.util.Arrays class can conveniently operate arrays, and all the methods it provides are static. Has the following functions:
Assign a value to the array: through the fill method.
Sort the array: use the sort method, in ascending order.
Compare arrays: Use the equals method to compare whether the element values in the array are equal.
Searching for array elements: The binarySearch method can perform a binary search operation on the sorted array.
Please see the table below for specific instructions:
serial number | Methods and instructions |
---|---|
1 | public static int binarySearch(Object[] a, Object key) uses a binary search algorithm to search for an object with a given value (Byte, Int, double, etc.) in the given array. The array must be sorted before calling. If the lookup value is contained in an array, returns the index of the search key; otherwise returns (-( insertion point ) - 1). |
2 | public static boolean equals(long[] a, long[] a2) Returns true if the two specified long arrays are equal to each other. Two arrays are considered equal if they contain the same number of elements and all corresponding pairs of elements in both arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. The same approach works for all other basic data types (Byte, short, Int, etc.). |
3 | public static void fill(int[] a, int val) assigns the specified int value to each element in the specified range of the specified int type array. The same approach works for all other basic data types (Byte, short, Int, etc.). |
4 | public static void sort(Object[] a) sorts the specified object array in ascending order according to the natural order of its elements. The same approach works for all other basic data types (Byte, short, Int, etc.). |