Java Chapter 2 Array
The concept and characteristics of arrays
- Array is a collection of multiple data of the same type arranged in a certain order, named with a name, and managed uniformly through numbering.
- Features
- The array itself is
Reference data type
, while the elements in the array can beany data type
, including basic data types and reference data types. - Creating an array object will allocate a whole block of memory
continuous space
. The amount of space occupied depends on the length of the array and the type of elements in the array. - The elements in the array are closely arranged and ordered in memory.
- The array name refers to the first address of this continuous space.
- An array, once initialized, has a certain length. array
Once the length is determined, it cannot be modified.
。 - We can directly call the element at the specified position by subscript (or index), which is very fast.
- The array itself is
one-dimensional array
Data type of element [] Name of one-dimensional array;
Data type of element One-dimensional array name[];
int[] arr;
int arr1[];
double[] arr2;
String[] arr3;
The declaration of the array needs to be clear:
(1) Dimensions of arrays: The symbol of arrays in Java is [], [] represents one dimension, and [][] represents two dimensions.
(2) Element type of the array: that is, what data type of data can be stored in the created array container. The type of the element can be any Java data type. For example: int, String, Student, etc.
(3) Array name: It is an identifier representing an array. The array name is actually a variable name, and it is named according to the variable naming convention. The array name is a reference data type variable because it represents a set of data.
Initialization of one-dimensional array
static initialization
-
If the initialization of an array variable and the assignment of array elements are performed at the same time, it is called static initialization.
-
Static initialization essentially uses static data (known at compile time) to initialize the array. At this time, the length of the array is determined by the number of static data.
-
One-dimensional array declaration and static initialization format 1:
Data type [] array name = new data type [] {element 1, element 2, element 3,...}; or Data type [] array name; Array name = new data type []{element 1, element 2, element 3,...};
- new: keyword, keyword used to create an array. Because the array itself is a reference data type, new is used to create the array entity.
int[] arr = new int[]{1,2,3,4,5};//Correct
//or
int[] arr;
arr = new int[]{1,2,3,4,5};//Correct
- One-dimensional array declaration and static initialization format 2:
Data type [] array name = {element 1, element 2, element 3...};//Must be completed in one statement and cannot be written in two statements
For example, define an array container that stores the integers 1, 2, 3, 4, and 5
int[] arr = {1,2,3,4,5};//Correct
int[] arr;
arr = {1,2,3,4,5};//Error
dynamic initialization
-
Concept: The initialization of array variables and the assignment of array elements are performed separately, which is dynamic initialization.
Format:
Data type of the elements stored in the array [] Array name = new Data type of the elements stored in the array [length]; or Data type stored in the array [] array name; Array name = new data type stored in the array [length];
-
Once the length is determined, it cannot be changed.
int[] arr = new int[5]; int[] arr; arr = new int[5];
Traversing a one-dimensional array
-
With for loop
public class Arraydemo1{ public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; //Iterate through the elements in the output array for(int i=0; i<; i++){//length represents the length of the array (arr[i]); } } }
default value
- Arrays are reference types. When we create an array using dynamic initialization, the element value is just the default value int[] and the default value is 0.
- For reference data types, the default initialization value is null (note that it is different from 0!)
two-dimensional array
-
If we can think of a one-dimensional array as a geometric
linear graphics
, then the two-dimensional array is equivalent toa form
, like a table in Excel or a Go board. -
For the understanding of two-dimensional arrays, we can think of it as a one-dimensional array array1 and existing as an element of another one-dimensional array array2.
- Tips: Among the two square brackets [][] in a two-dimensional array, the first one can be regarded as controlling the number of rows, and the second one can be regarded as controlling the number of columns.
int[][] arr; //arr is a two-dimensional array, which can be regarded as a one-dimensional array whose elements are int[] one-dimensional array type.
initialization
//recommend
The data type of the element [][] The name of the two-dimensional array;
//Not recommended
Data type of element: two-dimensional array name[][];
//Not recommended
Data type of element[] Two-dimensional array name[];
static initialization
Format:
int[][] arr = new int[][]{{3,8,2},{2,7},{9,0,1,6}};
Example:
int[][] arr = {{1,2,3},{4,5,6},{7,8,9,10}};//Declaration and initialization must be completed in one sentence
int[][] arr = new int[][]{{1,2,3},{4,5,6},{7,8,9,10}};
int[][] arr;
arr = new int[][]{{1,2,3},{4,5,6},{7,8,9,10}};
arr = new int[3][3]{{1,2,3},{4,5,6},{7,8,9,10}};//Error, static initialization of right new data type[] Numbers cannot be written in []
public class TwoDimensionalArrayInitialize {
public static void main(String[] args) {
//Storage multiple sets of scores
int[][] grades = {
{89,75,99,100},
{88,96,78,63,100,86},
{56,63,58},
{99,66,77,88}
};
//Storage multiple groups of names
String[][] names = {
{"Zhang San", "Li Si", "Wang Wu", "Zhao Liu"},
{"Liu Bei", "Guan Yu", "Zhang Fei", "Zhuge Liang", "Zhao Yun", "Ma Chao"},
{"Cao Pi","Cao Zhi","Cao Chong"},
{"Sun Quan","Zhou Yu","Lu Su","Huang Gai"}
};
}
}
dynamic initialization
If each piece of data in the two-dimensional array, or even the number of columns in each row, needs to be determined separately later, then dynamic initialization can only be used. Dynamic initialization methods are divided into two formats:
Format 1: Regular two-dimensional table: the number of columns in each row is the same
//(1) Determine the number of rows and columns
Data type of element [][] Two-dimensional array name = new Data type of element [m][n];
//Among them, m: indicates how many one-dimensional arrays this two-dimensional array has. In other words, how many rows does the two-dimensional table have?
//Among them, n: indicates the number of elements in each one-dimensional array. In other words, each row has one cell
//At this point, the array is created, the number of rows and columns is determined, and the elements also have default values.
//(2)Assign new values to the elements
Two-dimensional array name[row subscript][column subscript] = value;
int[][] arr = new int[3][2];
Format 2: Irregular: the number of columns in each row is different
//(1) First determine the total number of rows
Data type of element [][] Two-dimensional array name = new Data type of element [total number of rows][];
//At this time, only the total number of rows has been determined, and each row is now null.
//(2) Determine the number of columns in each row and create a one-dimensional array for each row
Two-dimensional array name [row subscript] = new data type of element [total number of columns in the row];
//At this time, the elements of the rows that have been new have default values, and the rows without new are still null.
//(3)Assign a value to the element again
Two-dimensional array name[row subscript][column subscript] = value;
int[][] arr = new int[3][];
- There are 3 one-dimensional arrays in the two-dimensional array.
- Each one-dimensional array has a default initialization value of null (note: different from format 1)
- These three one-dimensional arrays can be initialized separately: arr[0] = new int[3]; arr[1] = new int[1]; arr[2] = new int[2];
- Note:
int[][]arr = new int[][3];
//illegal
Two-dimensional array traversal
- Format:
Double for loop
for(int i=0; i
//1. Declare a two-dimensional array and determine the number of rows and columns.
int[][] arr = new int[4][5];
//2. Determine the value of the element
for (int i = 0; i < ; i++) {
for (int j = 0; j < ; j++) {
arr[i][j] = i + 1;
}
}
public class Test{
public static void main(String[] args) {
//Storage the scores of students in the three groups separately, using a two-dimensional array.
int[][] scores = {
{85,96,85,75},
{99,96,74,72,75},
{52,42,56,75}
};
("There are total " + +" group results.");
for (int i = 0; i < ; i++) {
("The" + (i+1) +" group has " + scores[i].length + " students, and the scores are as follows: ");
for (int j = 0; j < scores[i].length; j++) {
(scores[i][j]+"\t");
}
();
}
}
}
Common algorithms for arrays
Example 1:Array Statistics: Sum and Mean
public class TestArrayElementSum {
public static void main(String[] args) {
int[] arr = {4,5,6,1,9};
//Find the sum and mean
int sum = 0;//Because 0 plus any number does not affect the result
for(int i=0; i<; i++){
sum += arr[i];
}
double avg = (double)sum/;
("sum = " + sum);
("avg = " + avg);
}
}
Example 2:Find the total product of array elements
public class TestArrayElementMul {
public static void main(String[] args) {
int[] arr = {4,5,6,1,9};
//Find the total product
long result = 1;//Because 1 multiplied by any number does not affect the result
for(int i=0; i<; i++){
result *= arr[i];
}
("result = " + result);
}
}
Example 3:Find the number of even numbers in an array element
public class TestArrayElementEvenCount {
public static void main(String[] args) {
int[] arr = {4,5,6,1,9};
//Count even numbers
int evenCount = 0;
for(int i=0; i<; i++){
if(arr[i]%2==0){
evenCount++;
}
}
("evenCount = " + evenCount);
}
}
Example 4:Find the maximum value of array elements
public class TestArrayMax {
public static void main(String[] args) {
int[] arr = {4,5,6,1,9};
//Find the maximum value
int max = arr[0];
for(int i=1; i<; i++){//Here i starts from 1, which means max does not need to be compared with arr[0] again.
if(arr[i] > max){
max = arr[i];
}
}
("max = " + max);
}
}
Example 5:Find the maximum value and its first occurrence of the subscript:
public class TestMaxIndex {
public static void main(String[] args) {
int[] arr = {4,5,6,1,9};
//Find the maximum value and the first maximum value subscript
int max = arr[0];
int index = 0;
for(int i=1; i<; i++){
if(arr[i] > max){
max = arr[i];
index = i;
}
}
("max = " + max);
("index = " + index);
}
}
Reverse array elements
Implement ideas:Swap elements at symmetric positions in an array.
Find elements of array
1. Sequential search
public class TestArrayOrderSearch {
//Find the index where value first appears in the array
public static void main(String[] args){
int[] arr = {4,5,6,1,9};
int value = 1;
int index = -1;
for(int i=0; i<; i++){
if(arr[i] == value){
index = i;
break;
}
}
if(index==-1){
(value + "does not exist");
}else{
(value + "The subscript is " + index);
}
}
}
2. Binary search
//Binary search: This array must be ordered.
int[] arr3 = new int[]{-99,-54,-2,0,2,33,43,256,999};
boolean isFlag = true;
int value = 256;
//int value = 25;
int head = 0;//first index position
int end = - 1;//Tail index position
while(head <= end){
int middle = (head + end) / 2;
if(arr3[middle] == value){
("The specified element was found, the index is: " + middle);
isFlag = false;
break;
}else if(arr3[middle] > value){
end = middle - 1;
}else{//arr3[middle] < value
head = middle + 1;
}
}
if(isFlag){
("The specified element was not found");
}
Sorting algorithm
bubble sort
Sorting ideas:
-
Compare adjacent elements. If the first is greater than the second (in ascending order), swap them both.
-
Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. After this step is completed, the final element will be the largest number.
-
Repeat the above steps for all elements except the last one.
-
Keep repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers left to compare.
Dynamic demo:/zh/sorting
/*
1. Bubble sort (the most classic)
Idea: Each time the "adjacent (adjacent)" elements are compared, if they do not meet the target order (for example: from small to large),
Just swap them, and after multiple rounds of comparisons, sorting is finally achieved.
(For example: from small to large) In each round, the largest one can sink to the bottom, or the smallest one can rise to the top.
Process: arr{6,9,2,9,1} Goal: From small to large
First round:
The first time, arr[0] and arr[1], 6>9 does not hold, meeting the target requirements, no exchange
The second time, arr[1] and arr[2], 9>2 holds, which does not meet the target requirements, exchange arr[1] and arr[2] {6,2,9,9,1}
The third time, arr[2] and arr[3], 9>9 does not hold, meeting the target requirements, no exchange
For the fourth time, arr[3] and arr[4], 9>1 is established, which does not meet the target requirements. Exchange arr[3] and arr[4] {6,2,9,1,9}
All elements {6,9,2,9,1} in the first round have participated in the comparison and it is over.
The result of the first round: the first "first" maximum value of 9 sinks to the bottom (this time it is the subsequent 9 sinking to the bottom), that is, to the rightmost element of {6, 2, 9, 1, 9}
Second round:
For the first time, arr[0] and arr[1], 6>2 holds, which does not meet the target requirements. Exchange arr[0] and arr[1] {2,6,9,1,9}
The second time, arr[1] and arr[2], 6>9 does not hold, meeting the target requirements, no exchange
The third time: arr[2] and arr[3], 9>1 is established, which does not meet the target requirements, exchange arr[2] and arr[3] {2,6,1,9,9}
All unsorted elements {6,2,9,1} in the second round have participated in the comparison, and it is over.
The result of the second round: The "second" maximum value of 9 sinks to the bottom (this time it is the previous 9 sinking to the bottom), that is, to the rightmost element of {2,6,1,9}
Round 3:
For the first time, arr[0] and arr[1], 2>6 do not hold, meeting the target requirements, no exchange
The second time, arr[1] and arr[2], 6>1 is established, which does not meet the target requirements. Exchange arr[1] and arr[2] {2,1,6,9,9}
All unsorted elements {2, 6, 1} in the third round have participated in the comparison and it is over.
The result of the third round: the third maximum value 6 sinks to the bottom, that is, to the rightmost element of {2,1,6}
Round 4:
For the first time, arr[0] and arr[1], 2>1 is established, which does not meet the target requirements. Exchange arr[0] and arr[1] {1,2,6,9,9}
All unsorted elements {2,1} in the fourth round have participated in the comparison, and it is over.
The result of the fourth round: the fourth maximum value 2 sinks to the bottom, that is, to the rightmost element of {1,2}
*/
public class Test19BubbleSort{
public static void main(String[] args){
int[] arr = {6,9,2,9,1};
//Goal: From small to large
//The number of rounds of bubble sort = total number of elements - 1
//The number of rounds is multiple rounds, and the number of comparisons in each round is multiple. Double loops, that is, loop nesting, are needed.
//The outer loop controls the number of rounds, and the inner loop controls the number and process of comparisons in each round.
for(int i=1; i<; i++){ //The number of loops is -1 times/round
/*
Assumption=5
i=1, round 1, comparison 4 times
arr[0] and arr[1]
arr[1] and arr[2]
arr[2] and arr[3]
arr[3] and arr[4]
arr[j] and arr[j+1], int j=0;j<4; j++
i=2, round 2, compare 3 times
arr[0] and arr[1]
arr[1] and arr[2]
arr[2] and arr[3]
arr[j] and arr[j+1], int j=0;j<3; j++
i=3, round 3, compare 2 times
arr[0] and arr[1]
arr[1] and arr[2]
arr[j] and arr[j+1], int j=0;j<2; j++
i=4, round 4, comparison once
arr[0] and arr[1]
arr[j] and arr[j+1], int j=0;j<1; j++
int j=0; j<-i; j++
*/
for(int j=0; j<-i; j++){
//I hope arr[j] < arr[j+1]
if(arr[j] > arr[j+1]){
//Exchange arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
//Complete sorting and traverse the results
for(int i=0; i<; i++){
(arr[i]+" ");
}
}
}