Table of contents
1. What is an array?
Array (arry) is a storage model for storing multiple data of the same type
2. Definition of array
- Format 1: data type [ ] variable name
//例如
int[] arr
- Format 2: Data type variable name [ ]
int arr[]
3. Array initialization
Arrays in Java must be initialized before they can be used.
Initialization is to allocate memory space for the array elements in the array and assign a value to each array element.
1. Dynamic initialization
Dynamic initialization: only the length of the array is specified during initialization, and the system assigns the initial value to the array
- Format: data type [ ] variable name = new data type [array length]
int[] arr = new int[3];
2. Static initialization
Static initialization: only the length of the array is specified during initialization, and the system assigns the initial value to the array
- Format: data type [ ] variable name = new data type [array length]
int[] arr = new int[3];
3. Access to array elements
-
Array variable access method
-
Format: array name
-
Variable access method stored inside the array
-
Format: arrayname[index]
4. Multidimensional array
Two-dimensional array definition:
String[][] str = new String[3][4];
reference to a two-dimensional array
str[1][0];
5. Noteworthy
- Arrays can be passed as arguments to functions, or as return values from functions
- The java.util.Arrays class facilitates manipulation of arrays, and all methods provided by it are static.
- Assignment to the array: through the fill method.
Sort the array: by sort method, in ascending order.
Comparing arrays: use the equals method to compare whether the element values in the array are equal.
Find array elements: through the binarySearch method, binary search operations can be performed on the sorted array.