[JavaSE] Super-detailed explanation of arrays [understand array problems at one time]

I hope to communicate and learn from each other through the blog. If there are any mistakes, please correct me in the comment area.

An array is a collection of data elements of the same type, which are stored contiguously in memory (the meaning is the same as in the C language, so I won't repeat it here)

content

First, define the array

1. Static initialization

2. Dynamic initialization

3. Irregular definition of two-dimensional array

Where are arrays in Java memory?

Notice

Second, the length of the array and printing the array

Third, the array as a parameter of the method

pass parameters

What is a citation?

null

 Fourth, the tool class for operating arrays (java.util.Arrays)

1. Arrays.toString();

2. Arrays.copyOf();

3. Arrays.copyOfRange();

4. Arrays.clone();


First, define the array

1. Static initialization

数据类型[] 数组名称 = { 初始化数据 };
int[] arr = {1, 2, 3, 4, 5};
int[][] array = {
   
   {1,2,3},{4,5,6}};

Define an array with 5 elements in it, each element type is int 

2. Dynamic initialization

数据类型[] 数组名称 = new 数据类型 [] { 初始化数据 };

eg1. 

int[] arr2 = new int[]{1, 2, 3, 4, 5};
int[][] array2 = new int[][]{
   
   {1,2,3},{4,5,6}};

eg2.

int[] arr3 = new int[5];
int[][] array3 = new int[2][3];

In dynamic initialization, an array object is instantiated by new, there are a total of 5 elements in it, and each element type is int

The previous arr, arr2, arr3 are the names of the arrays, that is, the variable names, and the right side of the equal sign is the array object

When the array is created in eg2, there is no initial value assigned, then it is 0 (note the difference from the C language)

3. Irregular definition of two-dimensional array

int[][] array3 = new int[2][];

 This is to be distinguished from the C language. In the C language, the rows of the array can be omitted, but the columns cannot be omitted.

In Java, array rows must have, columns can be omitted, but columns cannot be automatically deduced

This definition means that the array has two rows, several columns are indeterminate, and the number of columns in each row in Java can be different , as follows:

int[][] array3 = new int[2][];
array3[0] = new int[2];
array3[1] = new int[3];

Where are arrays in Java memory?

We should answer this question rigorously, the array object is on the heap , but the array variables arr, arr2, arr3 are on the stack, which seems awkward, but it is the truth

8 basic types, which directly store the data we want to store, on the stack, but arr is a reference type, which stores the address of the object it points to

We illustrate by the following figure

eg. int[] arr = new int[]{1, 2, 3, 4, 5};

 we can verify

public static void main(String[] args) {
    int[] arr = new int[]{1, 2, 3, 4, 5};
    System.out.println(arr);
}

operation result:

Notice

 This is not a real address in the heap, it is processed by Java

Second, the length of the array and printing the array

Java is an object-oriented language. We pay attention to the object itself. In Java, an attribute of an array is length, which we can use directly, as follows:

public static void main(String[] args) {
    int[] arr = new int[]{1, 2, 3, 4, 5};
    int len = arr.length;
    System.out.println(len);
}

print array

Way 1:

public static void main(String[] args) {
    int[] arr = new int[]{1, 2, 3, 4, 5};
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
}

 operation result:

 Print a two-dimensional array:

public static void main(String[] args) {
    int[][] array = new int[][]{
   
   {1,2,3},{4,5,6}};
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j]);
        }
        System.out.println();
    }
}

 

The memory layout of two-dimensional arrays is very different from that of C language, as shown in the following figure:

Way 2:

for (int e : arr) {
    System.out.print(e + " ");
}

 There is one for loop in mode 2 :  the following is the array to be printed, and the front is the element type of the array to be printed

Two-dimensional array:

public static void main(String[] args) {
    int[][] array = new int[][]{
   
   {1,2,3},{4,5,6}};
    for (int[] cur : array) {
        for (int val : cur) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}

 

 Way 3:

You can also convert the array to a string and print the output

import java.util.Arrays;
public static void main(String[] args) {
    int[] arr = new int[]{1, 2, 3, 4, 5};
    String str = Arrays.toString(arr);
    System.out.println(str);
}

 

 Two-dimensional array:

public static void main(String[] args) {
    int[][] array = new int[][]{
   
   {1,2,3},{4,5,6}};
    System.out.println(Arrays.deepToString(array));
}

 

 

Third, the array as a parameter of the method

pass parameters

When we use an array to pass parameters, what should we receive?

The array variable is actually a reference. We pass it in the past and directly take the array variable to receive it (avoiding the overhead of passing the entire array in the past)

The following code:

public static void print(int[] array) {
    for (int i : array) {
        System.out.print(i + " ");
    }
}
public static void main(String[] args) {
    int[] arr = new int[]{1, 2, 3, 4, 5};
    print(arr);
}

 Icon:

 Two references point to the same block of memory

What is a citation?

Reference is actually equivalent to a pointer in C language, which is used to point to a piece of memory. We can find this piece of memory or this object by reference, and perform some series of operations on this object by reference

Emoticons: Image results for objects

 As shown below:

Java sets the array as a reference type. In this case, the subsequent array parameter transfer is only passed in the address of the array into the function parameter, which can avoid copying the entire array (the array may be long, so the copy overhead is will be big)

null

When the pointer in C language does not want to point to any variable after creation, it will point to NULL, representing the address of 0x00000000

Then there is such a situation in Java, we let the reference point to null, but the null here is not at the address of 0x00000000, but let the reference not point to any object

Emoji: Image result for empty object

int[] arr = null;

is equivalent to an invalid reference

When we operate on this reference, a NullPointerException will occur

public static void main(String[] args) {
    int[] arr = null;
    System.out.println(arr[0]);
}

 Fourth, the tool class for operating arrays (java.util.Arrays)

Java provides many methods for manipulating arrays, which is very convenient when writing code

Emoticons: Powerful Image Results

 When using it, import the package java.util.Arrays

1. Arrays.toString();

Convert the data in the array to a string

 In IDEA, you can see that Java has overloaded the toString method, so that it can operate on different types of arrays

function prototype

static String toString(int[] a)

 Returns a string representation of the contents of the specified array

Code example :

import java.util.Arrays;
public class Demo2 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        String str = Arrays.toString(arr);
        System.out.println(str);
    }
}

In this code, the data in the arr array is converted into a string by Arrays.toString(); (very convenient)

operation result:

 Mock implementation :

public static String toString(int[] arr) {
    String str = "[";
    for (int i = 0; i < arr.length - 1; i++) {
        str = str + arr[i] + ",";
    }
    if (arr.length != 0) {
        str = str + arr[arr.length - 1];   // 对最后一个元素做特殊处理
    }
    str = str + "]";
    return str;
}

Other types of arrays can be overloaded

2. Arrays.copyOf();

You can also use System.arraycopy();

copy array

This method does not simply perform operations such as arr = arr2, but creates a new object and copies the value in the original object to the new object. In this way, modifying the original array will naturally not affect the value of the new array.

function prototype 

static int[] copyOf(int[] original, int newLength)

 Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

Code example:

public static void main(String[] args) {
    int[] arr = {1,2,3,4,5};
    int[] arr2 = Arrays.copyOf(arr, arr.length);
    System.out.println(Arrays.toString(arr2));
}

Complete a deep copy of an array by calling Arrays.copyOf();

 The second parameter of this method can also be larger or smaller than the original array length

If the incoming newLength > arr.length, the rest will be filled with 0

If newLength < arr.length, copy from the beginning to the specified length

eg.

public static void main(String[] args) {
    int[] arr = {1,2,3,4,5};
    int[] arr2 = Arrays.copyOf(arr, 8);
    System.out.println(Arrays.toString(arr2));
    int[] arr3 = Arrays.copyOf(arr, 3);
    System.out.println(Arrays.toString(arr3));
}

 Simulation implementation

public static int[] copyOf(int[] arr, int newLength) {
    int[] array = new int[newLength];
    int minLength = arr.length < newLength ? arr.length : newLength;
    for (int i = 0; i < minLength; i++) {
        array[i] = arr[i];
    }
    return array;
}

Note : The array subscript cannot be out of bounds, and all three cases must be taken into account

3. Arrays.copyOfRange();

copy a range of an array

function prototype

static int[] copyOfRange(int[] original, int from, int to)

Copies the specified range of the specified array into a new array

code example

public static void main(String[] args) {
    int[] arr = {1,2,3,4,5};
    int[] arr2 = Arrays.copyOfRange(arr, 0, 5);
    System.out.println(Arrays.toString(arr2));
    int[] arr3 = Arrays.copyOfRange(arr, 2, 8);
    System.out.println(Arrays.toString(arr3));
    int[] arr4 = Arrays.copyOfRange(arr, 0, 0);
    System.out.println(Arrays.toString(arr4));
}

operation result:

 Note: The range in Java is basically a left-closed right-open interval

Simulation implementation

public static int[] copyOfRange(int[] arr, int fromIndex, int toIndex) {
    int[] newArray = new int[toIndex - fromIndex];
    int toIndexMin = arr.length < toIndex ? arr.length : toIndex;
    for (int i = fromIndex; i < toIndexMin; i++) {
        newArray[i - fromIndex] = arr[i];
    }
    return newArray;
}

4. Arrays.clone();

made a copy of the object (Object's clone method)

This is a shallow copy

Welcome everyone to pay attention! ! !

Learn to communicate together! ! !

Let's get programming to the end! ! !

--------------It's not easy to organize, please support three consecutive -------------------

Guess you like

Origin blog.csdn.net/weixin_46531416/article/details/122261697