Java basic syntax - array (insert and delete elements in the array with code)

Posted by snowrhythm on Sat, 29 Jan 2022 09:18:27 +0100

Java one-dimensional array and two-dimensional array definition and traversal, how to add and delete one-dimensional array with code

preface

In this article, we will introduce the use of arrays. We often use the double variable name when storing a student's grades, but in this way, we can only store one data at a time. In reality, there are often dozens of students in a class. Do we have to declare variables one by one? That's a little too troublesome, so we have the array we want to talk about next

1, What is an array?

   array is a container used to store multiple variables with the same data type, specific order and determined length. For example, if you want to store the scores of all students in a class, then this is a special container for storing student scores, which cannot be used to store other types. Therefore, the data types in the array are the same, and the number of students in a class is fixed, At the beginning of school, there are as many students as they come, which reflects the determination of length. Each student has a corresponding number on the student list according to the order in which they come. The student can be found through the number, which reflects the specific order

2, Definition of array

1. Dynamic initialization (specified length)

Data type of array [] Array name = new Data type of array[Array length];
//This is equivalent to declaring an object before creating it
 Data type of array [] Array name;
Array name = new Data type of array[Array length]

Example: create a double type array with a length of 30:

	double [] score = new score[30];
	//Equivalent to
	double [] score;
	score = new double[10];

2. Static initialization (specified content)

Data type of array [] Array name = new Data type of array[Array length] {Element 1,Element 2,......};
//Equivalent to
 Data type of array [] Array name = {Element 1,Element 2,......};

Example: save the number of weeks of a week to the array:

	String [] week = new score[]{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
	//Equivalent to
	String [] week = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

Matters needing attention:
  1. After specifying the length of the array, even if the array is assigned manually, the array will have default values according to different data types
     String default value: null
      byte/short/int/long default: 0
     float/double default value: 0.0
      boolean default: false
     char default value: (space)

3. Two dimensional array

   two dimensional array is used to store one-dimensional array. If one-dimensional array is regarded as a container for storing the same data type, two-dimensional array is a container for storing one-dimensional array, and you can access one-dimensional array and its internal elements in the same way as one-dimensional array

Dynamic initialization: data types [][] Data name = new data type [m][n]
  m Indicates how many one-dimensional arrays this two-dimensional array has
  n Represents the number of elements of each one-dimensional array
 Static initialization:
    data type [][] Data name = new data type[][]{One dimensional array 1,One dimensional array 2,......}
	data type [][] Data name = {{2,3},{1,1},{3,8}}

Example: accessing elements in a one-dimensional array:

int [][] a = {{3,3},{1,4,6},{3,8}};
//Represents an element with a subscript of 2 in a one-dimensional array with a subscript of 1
System.out.println(a[1][2])
//The output is 6

3, Traversal of array

   there are two methods for traversing an array. The length method of the array involves obtaining the length of the array. For example, if the element in the array is {1,2,3,4,5}, the output length after calling this method is 5. However, since the array subscript starts from 0, the subscript of the last number is 4

1.for loop value traversal output

   traversal of one-dimensional array:
  the implementation code is as follows:

int [] a = {1,2,5,342,234,22,42,3};
for (int i = 0; i < a.length; i++) {
    System.out.println(a[i]);
}

   a simple explanation: the index of the array starts from 0, and the i variable we need to use is the index of the elements in the array. Therefore, when traversing the array, the initial value of i can only be 0 (which should be distinguished from the previously written sum within 100). a.length is the length of the array. As explained earlier, the array has 8 elements, so the output is 8, i < a certain number is - 1 at most. i > a certain number is + 1 at most. Since the maximum subscript is 7, only 7 can be obtained here. The value of the array can be directly taken by the array name [the subscript number of the element]
   traversal of two-dimensional array:
   the traversal of a one-dimensional array requires a layer of loop, so the traversal of multiple one-dimensional arrays requires loop nesting. We explained in detail how to understand the external loop and internal loop through the 99 multiplication table (see Java basic syntax -- branch structure, loop structure and loop nesting (print 99 multiplication table) )The external loop here is each one-dimensional array, and the internal loop is the element in the one-dimensional array. When i = 0, first take out the first one-dimensional array in the two-dimensional array, and then enter the internal loop. The internal loop starts to traverse from the subscript j = 0, Until the last element of this one-dimensional array a[0] (representing the one-dimensional array with subscript 0 in the two-dimensional array).
  the implementation code is as follows:

int [][] a = {{3,3},{1,4,6},{3,8}};
for (int i = 0; i < a.length; i++) {
    for(int j = 0; j < a[i].length; j++){
    	System.out.println(a[i][j] + ",");
    }
    //Wrap every time you output a one-dimensional array
    System.out.println();
}

2. For each loop value traversal output

   Java also provides a way to directly get the value of each element starting from the element with subscript 0, that is, the for each loop. If you use IDEA as the editor, you can write the code quickly by directly entering iter + enter. Beginners are best to knock on both sides and get familiar with it
   traversal of one-dimensional array:

//i is a tool man. i will start with the element with subscript 0. Each cycle will assign the value of the element in the a array to itself
int [] a = {1,2,5,342,234,22,42,3};
for (int i : a) {
    System.out.println(i);
}

   traversal of two-dimensional array:
   the outer loop means to take the one-dimensional array ints from the two-dimensional array A. each ints represents each element of the two-dimensional array starting from the 0 subscript. Note that the ints at this time is a one-dimensional array, and then the internal loop takes the specific element anInt from the one-dimensional array ints and outputs it

int [][] a = {{3,3},{1,4,6},{3,8}};
for (int[] ints : a) {
	for (int anInt : ints) {
		System.out.print(anInt);
		System.out.print(",");
}

4, Addition and deletion of array

   because the array has the characteristic of fixed length, once the length is confirmed, it cannot be changed, just like a 2L water cup. After the length is confirmed, it can only hold 2L water. More will overflow and less will be empty, which makes it more troublesome to add and delete data in the array, but we also need to master how to use code to add and delete elements in the array

1. Insertion of array elements

   because the length in the array is fixed, when we add data at the specified position, the elements from the data will be squeezed out one by one until the last element is squeezed out of the container. Here we need to clarify three points: first, the process of moving the elements back in the array is actually the process of each element being covered by the previous element, It doesn't end until the last element is overwritten. Second, each element needs to hand over its own data before being overwritten. Third, only the data of the last element is really lost. The data of other elements is equivalent to being handed over to the next element, and only the last element is really overwritten. After the above three points are clear, we will know that the starting point of the program starts from the last element is overwritten
The implementation code is as follows:

//Add an element 666 where the subscript is 3
int [] a = {1,2,5,342,234,22,42,3};
for (int i = a.length - 1; i > 3; i--) {
    a[i - 1] = a[i];
    //Because the element of a[3] has been assigned to a[4], you can directly assign a value to the element at the specified position
    if(i == 4){
    	a[3] = 666;
    }
}

   similarly, we can rewrite the program into a method: insert the specified data for an integer array at the specified subscript. This method can use the overload of the method to pass in other types of arrays
The implementation code is as follows:

//Adds the specified element under the specified subscript of the array
public static void addArray(int [] a, int index, int data){
	for (int i = a.length - 1; i > index; i--) {
		a[i] = a[i - 1];
		if(i == index + 1){
			a[index] = data;
		}
	}
}

2. Deletion of array elements

   also because of the fixed length feature, after we delete the element with the specified subscript, the following element will fill in the deleted element, and the last element will be empty and filled with the default value of the data type. We also need to pay attention to three points: first, the process of moving the elements in the array forward, which is actually the process of each element being overwritten by the latter element, It doesn't end until the last element is left empty. Second, each element needs to hand over its own data before being overwritten. Third, only the deleted element is really lost, and the data of other elements is equivalent to handing over to the previous element. After the above three points are clear, we also know that the starting point of the program is that the deleted element is overwritten by the next element
The implementation code is as follows:

//Delete the element at the position with subscript 2 in the array
int [] a = {1,2,5,342,234,22,42,3};
for (int i = 2; i < a.length - 1; i--) {
    a[i] = a[i + 1];
    if(i == a.length - 2){
    	a[a.length - 1] = 0;
    }
}

   similarly, we can rewrite the program into a method: delete the elements of the array at the specified subscript. This method can use the overload of the method to pass in other types of arrays

//Specifies an array and deletes the elements under the specified subscript
public static void addArray(int [] a, int index){
	for (int i = index; i < a.length - 1; i--) {
		a[i] = a[i + 1];
		if(i == a.length - 2){
			a[a.length - 1] = 0;
		}
	}
}

Matters needing attention:
  1. Because the array assigns the latter element to the former element. If I < a.length - 1 is taken, when the value of I is the last subscript of the array, a[i] = a[i + 1] is executed at this time; Statement, I + 1 will exceed the maximum subscript of the array, and Java will report an array out of bounds exception. Therefore, at this time, I only needs to get the penultimate subscript to assign the value of the last element to the previous element
  2. When the index of the array is the index of the penultimate element, the value of the last element has been handed in. At this time, we can clear the value of the last element according to the data type of the array

summary

The above is what I want to talk about today. This paper introduces the definition and traversal of one-dimensional array and two-dimensional array, and how to add and delete one-dimensional array with code

Topics: Java JavaSE