Java essay record Chapter 3: array

Keywords: Java Back-end

preface

When using an array, remember that the subscript 0 is the first
Subscript 0 is the first
Subscript 0 is the first!!!
I've thought about this sentence for a long time, and I think it's best to put it at the beginning

This chapter is mainly about arrays. In actual use, if we want to declare a large number of data of the same data type, we can use arrays. Arrays are also divided into one-dimensional arrays and two-dimensional arrays. We can decide which to use according to the actual situation. In the object-oriented foundation - classes to be written in the next chapter, we can also bind data and objects, Data processing through one-dimensional array. Moreover, Java arrays are different from arrays in C language. Pointers and arrays can call each other in C language, but Java does not need to actively handle pointers, so it does not need to consider the security problems caused by operating data pointing to unallocated space.

array

Take a case close to reality as an example:

give an example

There are 30 students in each class. Each student has its own ID number (String type storage). Now write a program to traverse the student's ID and output it.

analysis

If you use the original idea, you will create 30 new String objects corresponding to the student's ID number one by one, but this operation cannot realize the circular traversal of data and is time-consuming and laborious. At this time, we can use arrays to store data.

code

If not through the array:

import java.util.UUID;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        String studentId01 = UUID.randomUUID().toString();
        String studentId02 = UUID.randomUUID().toString();
        String studentId03 = UUID.randomUUID().toString();
        String studentId04 = UUID.randomUUID().toString();
        String studentId05 = UUID.randomUUID().toString();
        // ... omit some boring operations
        String sutdentId28 = UUID.randomUUID().toString();
        String sutdentId29 = UUID.randomUUID().toString();
        String sutdentId30 = UUID.randomUUID().toString();

        System.out.println(studentId01);
        System.out.println(studentId02);
        System.out.println(studentId03);
        // ... omit some boring operations
        System.out.println(sutdentId28);
        System.out.println(sutdentId29);
        System.out.println(sutdentId30);
    }
}

The code is bloated and ugly, and the operation is complex.

(UUID is mainly used to obtain an almost non duplicate data. It is generally used to randomly name a large number of non duplicate data. Here, you can write them one by one. You can also practice the input and output described in the previous chapter. The effect is better: b)

If an array is used:

import java.util.UUID;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        // Data of 30 students
        String[] studentId = new String[30];

        for(int i = 0 ; i < studentId.length ; i++){
            studentId[i] = UUID.randomUUID().toString();
            System.out.println("The first" + i + "The random number of students is:" + studentId[i]);
        }
    }
}

This greatly reduces the amount of code and makes it more intuitive. More details will be given below.

One dimensional array

Array declaration

The first is the declaration of the array:

[data type] [array name] [] = new [data type] [array length]]

Of course, the following methods can also be used:

[data type] [[array name] = new [data type] [[array length]]

(if the formula is set, replace the square brackets together, but pay attention to the declaration method of the code in the above. It turns out that some people always ask me why I can't use square brackets, or delete the square brackets and ask me why I can't use them, so I have to write two layers of square brackets where square brackets are needed... I'll keep this paragraph. I'll go straight to whoever comes to me with the declaration error later Throw this paragraph in his face)

The first method mainly emphasizes that the declared array is an array of the data type. If it is not initialized, the subsequent declared variables are only the data of the corresponding data type.
The second method mainly emphasizes that the declared array is an array of this array type. If it is not initialized, the subsequent declared variables are arrays of corresponding data types.
(this paragraph is the key!!!)

give an example

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        // Data of 30 students
        String[] abc = new String[30], bud = new String[30], str = new String[30];

        String sStr[] = new String[30], s[] = new String[30], s1[] = new String[30];

    }
}

This has the same effect on the declaration of array variables. If you want to declare a large number of arrays, the first method is recommended. If you want to declare a large number of basic data and only a small number of arrays, the second method is recommended.

Call of array data

import java.util.UUID;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        // Data of 30 students
        String[] studentId = new String[30];

        for(int i = 0 ; i < studentId.length ; i++){
            studentId[i] = UUID.randomUUID().toString();
            System.out.println("The first" + i + "The random number of students is:" + studentId[i]);
        }
    }
}

It is not difficult to see that the array is mainly realized through square brackets to read the data. Accordingly, when calling the data, it is through

[array name] [subscript]

This meaning is also well understood. It is to specify the N + 1st data under the array. Why n+1 is because, like arrays in Java and C, subscripts are allocated from subscript 0, that is, the declaration length is 30, but the actual available subscript range is 0 ~ 29, not 1 ~ 30. This is very important. For example, if you allocate n memory, the subscript will reach the position of n-1, and there will be no data with subscript n. at this time, an exception will be reported that the array is out of bounds.

Properties of the array itself

import java.util.UUID;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        // Data of 30 students
        String[] studentId = new String[30];

        for(int i = 0 ; i < studentId.length ; i++){
            studentId[i] = UUID.randomUUID().toString();
            System.out.println("The first" + i + "The random number of students is:" + studentId[i]);
        }
    }
}

In the above code, you should also notice that the loop condition inside the loop is I < studentId.length, which is the attribute of the array itself.
In Java, based on the idea of object-oriented programming, everything belongs to objects. An array is composed of a series of objects, but similarly, the array itself is also an object (yes, it is a doll). Theoretically, it can set an infinite dimensional array, but who uses it like this under normal circumstances... It won't be used like this.
All arrays will have a length attribute, that is, the length of the array defined at the beginning. When some editors use '.' to open the automatic supplementary completion function, many other methods are the methods of the Object class (which is also the embodiment of the array as an Object), which will play a certain role in subsequent development. In the early stage, we can mainly understand the length attribute.

Two dimensional array

Array declaration

Similar to a one-dimensional array
Declaration of array:

[data type] [array name] [] [] = new [data type] [[array one-dimensional length]] [[array two-dimensional length]]

Of course, the following methods can also be used:

[data type] [] [] [array name] = new [data type] [[array one-dimensional length]] [[array two-dimensional length]]

It should be noted here that when declaring a two-dimensional array, the one-dimensional length of the array must be declared, but the two-bit length can not be declared.

give an example

import java.util.UUID;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        // Data of 30 students
        String[][] studentId = new String[6][30];
        // This declaration is to declare the length of both dimensions
        String[][] studentName = new String[6][];
        // Such a declaration is also legal, but the length of the corresponding array should be declared in subsequent calls
        String[] student = new String[30],nStudent[] = new String[6][];
        // If it is declared in this way, student is a one-dimensional array and NStudent is a two-dimensional array. Although it can be declared in this way, it is not recommended because it is easy to be confused.
    }
}

Call of two-dimensional array data

Similar to the one-dimensional array, the code is directly lost here:

import java.util.UUID;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        // Data of 30 students
        String[][] studentId = new String[6][30];
        
		for(int i = 0 ; i < studentId.length ; i++){
			
			for(int j = 0 ; j < studentId[i].length ; j++){
				studentId[i][j] = UUID.randomUUID().toString();
				System.out.println((i+1) + "Class" + j + "The random number of students is:" + studentId[i][j]);
			}
			System.out.println();
		}

    }
}

Properties of the two-dimensional array itself

Similar to the one-dimensional array, the length attribute is mainly used, but it must be noted that when using the length attribute, if you want to call the length of the one-dimensional array, you must declare the specified subscript, because Java allows the length of each one-dimensional array in the two-dimensional array to be different, so the corresponding length cannot be found without specifying the subscript.

Multidimensional array

The application of multi-dimensional array is similar to the difference between two-dimensional array and one-dimensional array. You can try it according to your own understanding. Most of the time, two-dimensional array can meet your needs, so we won't repeat it too much. (similarly, if you have any questions, you can leave a message in the comments or send me a private letter directly. I will reply when I see it.)

Common array operation methods

Java has its own array operation class, the Arrays class. The most commonly used class is the sort() sorting method. It should be noted that if the Arrays of custom class objects want to use the Arrays.sort() method, it needs to implement the comparable < T > interface. I won't talk about it in detail here. I'll explain it later after talking about the basics of classes and objects.

Usage example of Arrays.sort() method

import java.util.Arrays;

/**
 * @author Silence_Lurker Latent silence
 */
public class App {
    public static void main(String[] args) {
        int[] i = new int[] { 1, 2, 3, 4, 8, 5, 2, 79 };

        Arrays.sort(i);

        System.out.println(Arrays.toString(i));

    }
}

summary

That's what we're going to talk about today,

I wish you all a relaxed and happy learning of Java.

Posted by rage2021 on Fri, 12 Nov 2021 13:45:15 -0800