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};omitted new int[] The abbreviated form of 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 Indicates 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
Array index from 0 To start, 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]);Access to a non-existent index will throw a 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 A loop can obtain both the index and the element value.
Using enhanced for loops
for (int number : numbers) {
System.out.println(number);
}enhance for Loops are suitable for scenarios where only element values are read, and the current index cannot be obtained directly.
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;
}
}Usually used directly in actual development Arrays.sort()。
random number
Random class
nextInt(bound) generate from 0 to bound - 1 integer of.
Random random = new Random();
int number1 = random.nextInt(10); // 0~9
int number2 = random.nextInt(6) + 5; // 5~10the following code uses Fisher-Yates Thoughts disrupt 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 greater than or equal to 0.0 and less than 1.0 the double value.
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~5two-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 length of the first array is 3, the lengths of the three inner arrays are 3、3、2。
Dynamic initialization of two-dimensional arrays
Create only outer arrays
int[][] matrix = new int[3][];This code only creates a code that has a length of 3 outer array of. at this time matrix[0]、matrix[1]、matrix[2] are null, 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 a code that has a length of 3 , and three outer arrays of lengths of 2 , a total of four array objects have been created.

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]); // 5Before accessing elements, make sure that the inner array is not a null, and neither index crosses 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 enhancements 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, you should use the length, cannot be assumed that each line is 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);Arrays.copyOfRange() The ending index of 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() Require the array to be 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() You can copy the specified range of the source array to the specified location 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 code above indexes the source array 2、3 Position to the target array index 4、5 Location.
If you enjoyed this, leave a comment~