Array
Array Overview
Arrays are used to hold a set of data of the same type. Each data in an array is called an element, and each element has a corresponding index.
Java arrays have the following characteristics:
- An array can only hold elements of the same data type.
- The length of the array is fixed after creation and cannot be directly changed.
- Arrays can quickly access elements through indexes.
- When you insert or delete elements in the middle of an array, you usually need to move other elements.
When you need to expand the size of an array, you usually create a new, larger array and copy the elements in the original array.
one-dimensional array
Definition of array variables
It is recommended to write square brackets after the data type:
int[] numbers;
double[] prices;
String[] names;
You can also write square brackets after the variable name, but this is not recommended.
int numbers[];
Array is of reference type.
Creation of arrays
Static initialization of one-dimensional array
Static initialization is to directly specify element values when declaring array variables, and the array length is determined by the number of elements.
int[] numbers = {2, 5, 7, 8};
You can also write in full form:
int[] numbers = new int[] {2, 5, 7, 8};
The abbreviated form of omitting new int[] can only be used while declaring a variable.
Dynamic initialization of one-dimensional array
Dynamic initialization first specifies the array length, and the system sets default values for each element.
int[] numbers = new int[3];
The default values for different types of array elements are as follows:
| Element Type | Default Value |
|---|---|
| Integer Type | 0 |
| Floating Point Type | 0.0 |
char | \u0000 |
boolean | false |
| Reference Type | null |
Memory model of arrays
Basic type variables directly hold basic type values; reference type variables hold references to objects. The specific memory size of the reference variable is determined by the JVM implementation and running mode, and cannot simply be regarded as fixed to a certain number of bytes.

null means that the reference variable does not currently point to any object and can only be assigned to reference type variables.
String text = null;
int[] numbers = null;
After the array object is created, it is located in heap memory, and the array variable holds a reference to the array object.
String[] names = new String[] {"ab", "cd", "e"};

Access array elements
The array index starts from 0, and the maximum index is array.length - 1.
int[] numbers = {3, 5, 6, 4, 25, 7, 3, 8, 9};
System.out.println(numbers[0]);
numbers[0] = 30;
System.out.println(numbers[numbers.length - 1]);
Visiting a non-existent index throws ArrayIndexOutOfBoundsException.

walk the array
Use a normal for loop
int[] numbers = {3, 5, 6, 4, 25, 7, 3, 8, 9};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Ordinary for loops can obtain both index and element values.
Using enhanced for loops
for (int number : numbers) {
System.out.println(number);
}
The enhanced for loop is suitable for scenarios where only element values are read, and the current index cannot be directly obtained.
Maximum, minimum and sum
The first element cannot be read directly when the array is empty, so the following writing requires the array to contain at least one element.
int[] numbers = {3, 5, 6, 4, 25, 7, 3, 8, 9};
int max = numbers[0];
int min = numbers[0];
int sum = 0;
for (int number : numbers) {
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
sum += number;
}Find elements
Scanner scanner = new Scanner(System.in);
int target = scanner.nextInt();
int[] numbers = {3, 5, 6, 4, 25, 7, 3, 8, 9};
boolean found = false;
for (int number : numbers) {
if (number == target) {
found = true;
break;
}
}
System.out.println(found ? "有" : "没有");array copy
The following code copies the elements of the original array into the new array in reverse order.
int[] source = {3, 5, 6, 4, 25, 7, 3, 8, 9};
int[] target = new int[source.length];
for (int i = 0; i < source.length; i++) {
target[i] = source[source.length - 1 - i];
}
sort
selection sort
int[] numbers = {3, 5, 6, 4, 25, 7, 2, 8, 9, 11};
for (int i = 0; i < numbers.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[j] < numbers[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}bubble sort
int[] numbers = {3, 5, 6, 4, 25, 7, 2, 8, 9, 11};
for (int i = 0; i < numbers.length - 1; i++) {
boolean swapped = false;
for (int j = 0; j < numbers.length - 1 - i; j++) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}Arrays.sort() is usually used directly in actual development.
random number
Random class
nextInt(bound) generates integers from 0 to bound - 1.
Random random = new Random();
int number1 = random.nextInt(10); // 0~9
int number2 = random.nextInt(6) + 5; // 5~10
The following code uses the Fisher-Yates idea to shuffle the array more evenly than swapping it with any position each time.
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = numbers.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int temp = numbers[i];
numbers[i] = numbers[index];
numbers[index] = temp;
}
Math.random()
Math.random() returns a double value greater than or equal to 0.0 and less than 1.0.
int number1 = (int) (Math.random() * 10); // 0~9
int number2 = (int) (Math.random() * 6) + 5; // 5~10
int number3 = (int) (Math.random() * 11) - 5; // -5~5
two-dimensional array
Definition of two-dimensional array
The elements of a two-dimensional array are still one-dimensional arrays, so Java’s two-dimensional array is essentially an “array of arrays.”
int[][] matrix;
It can also be written in the following form, but it is not recommended:
int matrix[][];
Creating a two-dimensional array
Static initialization of two-dimensional arrays
Static initialization assigns values to array elements while creating an array.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8}
};
You can also write in full form:
int[][] matrix = new int[][] {
{1, 2},
{3, 4, 5}
};
The outer layer length of the first array is 3, and the lengths of the three inner layers are 3, 3, and 2 respectively.
Dynamic initialization of two-dimensional arrays
Create only outer arrays
int[][] matrix = new int[3][];
This code only creates an outer array of length 3. At this time, matrix[0], matrix[1], and matrix[2] are all null, and the inner array has not yet been created, so only one array object has been created in total.

Inner arrays of different lengths can be created to form irregular two-dimensional arrays.
matrix[0] = new int[2];
matrix[1] = new int[4];
matrix[2] = new int[1];
Create both outer and inner arrays simultaneously
int[][] matrix = new int[3][2];
This code creates an outer array of length 3 and three inner arrays of length 2, creating a total of four array objects.

It is equivalent to creating the outer array first, and then creating three inner arrays separately:
int[][] matrix = new int[3][];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = new int[2];
}
Access to two-dimensional array elements
Use two indexes to access two-dimensional array elements. The first index locates the inner array, and the second index locates the elements in the inner array.
int[][] matrix = {
{1, 2},
{3, 4, 5}
};
System.out.println(matrix[1][2]); // 5
Before accessing elements, make sure that the inner array is not null and that neither index exceeds the boundary.
Traversal of two-dimensional arrays
int[][] matrix = {
{1, 2},
{3, 4, 5}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}You can also use the enhanced for cycle:
for (int[] row : matrix) {
for (int value : row) {
System.out.println(value);
}
}
Searching for two-dimensional arrays
int[][] matrix = {
{1, 2},
{3, 4, 5}
};
int target = 4;
boolean found = false;
outer:
for (int[] row : matrix) {
for (int value : row) {
if (value == target) {
found = true;
break outer;
}
}
}
System.out.println(found ? "有" : "没有");Deep copy of a two-dimensional array
Copying only the outer array causes the old and new two-dimensional arrays to share the inner array. To achieve independent copies, you need to continue copying each inner array.
int[][] source = {
{1, 2},
{3, 4, 5}
};
int[][] target = new int[source.length][];
for (int i = 0; i < source.length; i++) {
target[i] = Arrays.copyOf(source[i], source[i].length);
}irregular two-dimensional array
Java allows different lengths for each inner array.
int[][] matrix = new int[3][];
matrix[0] = new int[] {1, 2};
matrix[1] = new int[] {3, 4, 5};
matrix[2] = new int[] {6};
When traversing an irregular two-dimensional array, the length of the current inner array should be used, and each row cannot be assumed to be the same length.
Arrays tool class
copy array
int[] source = {4, 3, 2, 6, 7, 9, 1, 10, 11};
int[] copy = Arrays.copyOf(source, source.length);
The ending index of Arrays.copyOfRange() is not included in the replication scope.
int[] part = Arrays.copyOfRange(source, 0, 5);
sorted array
int[] numbers = {4, 3, 2, 6, 7, 9, 1, 10, 11};
Arrays.sort(numbers);
binary search
Arrays.binarySearch() requires that arrays have been sorted according to the same rules. Returns a non-negative index when an element is found and a negative index when not found.
int[] numbers = {4, 3, 2, 6, 7, 9, 1, 10, 11};
Arrays.sort(numbers);
if (Arrays.binarySearch(numbers, 8) >= 0) {
System.out.println("有");
} else {
System.out.println("没有");
}
System.arraycopy()
System.arraycopy() can copy the specified range of the source array to the specified position of the target array.
int[] source = {1, 2, 3, 4, 5, 6, 7};
int[] target = new int[10];
System.arraycopy(source, 2, target, 4, 2);
System.out.println(Arrays.toString(target));
The above code copies the elements at positions 2 and 3 in the source array indices 4 and 5.
If you enjoyed this, leave a comment~