Make writing a habit together! This is the third day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.


⭐️ ⭐️

This article introduces you to Java array usage and references. We all know that the element types in an array are the same, which gives it great ability to handle the same data type, so you can see how important it is. Java uses arrays differently from C, as you can see from the way arrays are defined. Let’s take a look.

📒 blog homepage: not seen flower smell blog homepage 🎉 welcome to pay attention to 🔎 like 👍 collect 🎉 🎉 message 📒 📆 Nuggets debut: 🌴 April 4, 2022 🌴 ✉️ Perseverance and hard work will be exchanged for poetry and distance! 💭 refer to books: 📚 “Java programming ideas”, 📚 “Java core technology” 💬 refer to online programming website: 📚 niuke.com SILVER force to deduct the code cloud of the blogger gitee, usually the program code written by the blogger are in it. Github of the blogger, the program code written by the ordinary blogger is in it. 🍭 author level is very limited, if you find mistakes, be sure to inform the author in time! Thank you, thank you!


🎨1. Basic usage of Java arrays

🎳1.1 How arrays are defined

🍁 Method 1:


The data type [ ] The variable name =   { The element 1 . The element 2 . The element 3 . . . . . The element n } ; Data type []\ variable name \ =\ {element 1, element 2, element 3… , the element n \};


i n t [ ]   a r r   =   { 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 0 } ; Int \ arr \ [] = \ \,2,3,4,5,6,7,8,9,0 \ {1};

🍁 Mode 2:


The data type [ ] The variable name =   n e w   i n t [ ] { The element 1 . The element 2 . The element 3 . . . . . The element n } ; Data type []\ variable name \ =\ new\ int[]\{element 1, element 2, element 3… , the element n \};


i n t [ ]   a r r   =   n e w   i n t [ ] { 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 0 } ; Int []\ arr\ =\ new\ int[]\{1,2,3,4,5,6,7,8,9,0\};

❗️new cannot specify the number of elements in parentheses, must be empty!

🍁 method 3: Data type [] variable name = new int[number of elements]; Data type []\ variable name \ =\ new\ int[number of elements]; \ (all elements of array will be initialized to 0) Data type [] variable name = new int[number of elements]; (All elements of the array are initialized to 0)

🎳1.2 Creation and use of arrays

🍁 array creation:

int[] data1 = {1.2.3.4.5.6.7.8.9.0};
int[] data2 = new int[] {1.2.3.4.5.6.7.8.9.0};
int[] data3 = new int[10];
Copy the code

🍁 array usage:

import java.util.Arrays;

public class TestBlog {
    public static void main(String[] args) {
        // Create an array
        int[] arr = new int[] {1.2.3.4.5.6.7.8.9.0};
        // Access the array length
        System.out.println(arr.length);
        // Access an array element
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);
        Foreach; foreach; toString

        // Method 1: for loop
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "");
        }
        System.out.println();
        // Method 2: foreach loop
        for (int a: arr) {
            System.out.print(a + "");
        }
        System.out.println();
        // Method 3: toString functionSystem.out.println(Arrays.toString(arr)); }}Copy the code

For array traversal 2:

for(Accept variable: array) {// Statement block;
	// This method does not get subscripts
}
Copy the code

For traversal mode 3:toStringIs a JavaArraysClass to convert an array to a string.Separate elements with brackets[]Wrap all elements of array!

🎨2. References to Java types

🎳2.1 Reference type

In Java, an array is actually an object, and we know that the keyword new is used in both ways when we define an array. The keyword is instantiating a class, instantiating an object, and using a type that accepts the value of the instantiated object is a reference type. The “value of the instantiated object” is actually an address that points to the array (object). For example, the x variable defined below defines an array. The x is the reference variable. This is a little bit like a pointer in C, but it’s not a pointer, and the reference variable is a value, in this case, the address of the array. We know that the x variable that we defined is local so it gets generated on the stack, and the array (object) gets created on the heap. Null refers to an empty reference, similar to NULL in C, indicating an invalid memory location. Since this memory is invalid, it must not be read or written to the space to which this memory refers. Note: There is no Java convention for null to be associated with memory at address 0.

Data type [] Variable name =new int[Number of elements]; All elements of the array are initialized to0)
int[] x = new int[3];
x[0] = 10;
x[1] = 20;
x[2] = 30;
Copy the code

A reference is essentially just an address. Java sets arrays as reference types, so that subsequent array arguments are simply passed the address of the array to the function parameter. This avoids copying the entire array (the array can be long, which can be expensive to copy). Let’s use an array parameter example to further understand the reference.

🎳2.2 Array parameter passing

public class TestBolg {
    public static void arrFunc(int[] arr) {
        if (arr == null) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i] = 10 * (i+1); }}public static void main(String[] args) {
        int[] x = new int[3]; arrFunc(x); System.out.println(Arrays.toString(x)); }}Copy the code

Passing a reference variable to an array is passing the value of a reference variable to a method parameter. Since the reference variable holds the address of the object, the method modifies or reads the array (the instantiated object) based on the passed parameter, changing the value of the elements in the array. This is referred to as passing.

🎳2.3 Learn about JVM partitioning

🎨3.Java array applications

🎳3.1 Use arrays to average and swap two numbers

public class AvgSwap {
    public static void swap(int[] data) {
        int tmp = data[0];
        data[0] = data[1];
        data[1] = tmp;
    }
    public static double avg(int[] data) {
        int sum = 0;
        for (int i = 0; i < data.length; i++) {
            sum += data[i];
        }
        return 1.0 * sum / data.length;
    }

    public static void main(String[] args) {
        int[] swap = {22.33};
        int[] avg = {1.2.3.4.5.6.7.8.9.0};
        System.out.println("Before data exchange: A =" + swap[0] + ", b = " + swap[1]);
        swap(swap);
        System.out.println("After data exchange: A =" + swap[0] + ", b = " + swap[1]);
        System.out.println("Array average is:"+ avg(avg)); }}Copy the code

🎳3.2 Copying an array

import java.util.Arrays;

public class Copy {
    public static int[] copy(int[] arr) {
        if (arr == null) {
            return null;
        }
        int[] copy = new int[arr.length];// Create an array
        for (int i = 0; i < arr.length; i++) {
            copy[i] = arr[i];// Iterate over the copy
        }
        return copy;
    }
    public static void main(String[] args) {
        int[] arr1 = {1.2.3.4.5.6.7.8.9};
        System.out.println("Array 1:");
        System.out.println(Arrays.toString(arr1));
        int[] arr2 = copy(arr1);
        System.out.println("Array 2:"); System.out.println(Arrays.toString(arr2)); }}Copy the code

Of course the Java Arrays class has built-in copy methods:


s t a t i c The data type [ ]   c o p y O f ( The data type [ ]   o r i g i n a l .   i n t   n e w L e n g t h ) Static \ data type []\ copyOf(data type []\ original,\ int\ newLength)

Copies the specified array, truncated or populated (if necessary) with zero so that the copy has the specified length.


s t a t i c The data type [ ]   c o p y O f R a n g e ( The data type [ ]   o r i g i n a l .   i n t   f r o m .   i n t   t o ) Static \ data type []\ copyOfRange(data type []\ original,\ int\ from,\ int\ to)

Copies the specified range [from, to] of the specified array into the new array.


s t a t i c   v o i d   a r r a y c o p y ( O b j e c t   s r c .   i n t   s r c P o s .   O b j e c t   d e s t .   i n t   d e s t P o s .   i n t   l e n g t h ) static\ void\ arraycopy(Object\ src,\ int\ srcPos,\ Object\ dest,\ int\ destPos,\ int\ length)

Object SRC indicates the source array, srcPos indicates the subscript position from the source array, Object Dest indicates the target array, destPos indicates the subscript position from the target array, and Length indicates the number of array elements to be copied.

If you look carefully at the source code of this method, you will find that this method is modified by Native, which means that this method is implemented using C/C++. Copies an array in the specified source array from the specified location to the specified location in the target array.


An array of . c l o n e ( ) Array name. The clone ()

The last option is to create and return a copy of the object using the array name.clone. The precise meaning of “copy” may depend on the class of the object. Because an array is an object when instantiated, this method returns an array of the corresponding type, so use this method for copying.

import java.util.Arrays;

public class Copy {

    public static void main(String[] args) {
        int[] arr1 = {1.2.3.4.5.6.7.8.9};
        System.out.println("arr1:" + Arrays.toString(arr1));
        int[] arr2 = Arrays.copyOf(arr1, arr1.length);
        System.out.println("arr2:" + Arrays.toString(arr2));
        int[] arr3 = Arrays.copyOf(arr1, arr1.length * 2);
        System.out.println("arr3:" + Arrays.toString(arr3));
        int[] arr4 = Arrays.copyOfRange(arr1, 1.5);
        System.out.println("arr4:" + Arrays.toString(arr4));
        int[] arr5 = new int[arr1.length];
        System.arraycopy(arr1, 0, arr5, 0, arr1.length);
        System.out.println("arr5:" + Arrays.toString(arr5));
        int[] arr6 = arr1.clone();
        System.out.println("arr6:"+ Arrays.toString(arr6)); }}Copy the code

In addition, a copy of the array is usually shallow copy, because everything in the Java object, the object of the copy is shallow, and the array is also a kind of object, unless the human factors make a deep copy, if in the array as simple data types are generally deep copy, if in the array are generally shallow copy for reference types.

🎳3.3 Array conversion string

I’m sure you’ve already seen the use of the arrays.toString method, which converts an array to a parenthesized string! Now let’s simulate this method:

public class StringArray {
    public static String myToString(int[] arr) {
        if (arr == null) {
            return "[]";// empty reference returns []
        }
        String str = "[";// Initialize the string as [
        for (int i = 0; i < arr.length - 1; i++) {
            str += arr[i] + ",";// Notice that there is no comma after the last array element
        }
        str += arr[arr.length - 1] + "]";// add the last element to the list.
        return str;
    }
    public static void main(String[] args) {
    int[] arr = {1.2.3.4.5.6.7.8.9}; System.out.println(myToString(arr)); }}Copy the code

🎳3.4 Array lookup

⛳️3.4.1 Sequential Search

Sequential lookup is the easiest way to do this, simply iterating through the array.

public class Search {
    public static void main(String[] args) {
        // Find the subscripts of the elements in sequence, if not, the output is not found
        int[] arr = {1.2.3.4.5.6.7.8.9};
        int k = 7;
        int flag = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == k) {
                System.out.println("Found it! Subscript:" + i);
                flag = 1;
                break; }}if (flag == 0) {
            System.out.println("Not found!); }}}Copy the code

⛳️3.4.2 Binary Search

Then there is the already familiar binary search:

public class BinSearch {
    public static int binSearch(int[] arr, int k) {
        if (arr == null) {
            return -1;
        }
        int left = 0;
        int right = arr.length - 1;
        int mid = left + (right - left) / 2;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (k > arr[mid]) {
                left = mid + 1;
            }
            else if (k < arr[mid]) {
                right = mid - 1;
            }
            else {
                returnmid; }}return -1;
    }
    public static void main(String[] args) {
        int[] arr = {1.2.3.4.5.6.7.8.9};
        int k = 7; System.out.println(binSearch(arr, k)); }}Copy the code

🎳3.5 Array arrangement

⛳️3.5.1 Checking whether an Array is in order

Use two counting chess for counting (counting from 1), traversing the array of numbers are not less than the previous item, the array after the item is not less than the previous item independent counting, if the counting result is exactly equal to the length of the array result, the array is ordered.

public class ArraryOrder {
    public static boolean arrOrder(int[] arr) {
        if (arr == null) {
            return false;
        }
        int cnt1 = 1;
        int cnt2 = 1;
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] <= arr[i+1]) {
                cnt1++;
            }
            if (arr[i] >= arr[i+1]) { cnt2++; }}if (cnt1 == arr.length || cnt2 == arr.length) {
            return true;
        }
        else {
            return false; }}public static void main(String[] args) {
        int[] arr1 = {1.2.3.4.5.6.7.8.9};
        int[] arr2 = {9.8.7.6.5.4.3.2.1};
        int[] arr3 = {2.1.4.7.5.9.8.3.6}; System.out.println(arrOrder(arr1)); System.out.println(arrOrder(arr2)); System.out.println(arrOrder(arr3)); }}Copy the code

⛳️3.5.2 Array Reverse

Double pointer, interchanging the left and right elements in turn.

import java.util.Arrays;

public class ReverseArr {
    public static void rever(int[] arr) {
        if (arr == null) {
            return;
        }
        int l = 0;
        int r = arr.length - 1;
        while (l < r) {
            inttmp = arr[l]; arr[l] = arr[r]; arr[r] = tmp; l++; r--; }}public static void main(String[] args) {
        int[] arr = {1.2.3.4.5.6.7.8.9};
        System.out.println("Before reverse order:");
        System.out.println(Arrays.toString(arr));
        System.out.println("After reverse order:"); rever(arr); System.out.println(Arrays.toString(arr)); }}Copy the code

⛳️3.5.3 Bubble Sort (ascending)

If the first element is larger than the last, swap. If not, the largest element is placed at the end of each sort. If you want to sort all the elements, subtract the number of elements in the array by one sort. Size = 1; size = 1; size = 1; size = 1; size = 1; size = 1 As the number of comparisons decreases step by step, if this is the ith order, the number of comparisons required is size-1-i. For example, bubble sorting of 10 elements requires a total of 9 sorting operations. The first operation requires 9 sorting and comparison operations, the second 8 sorting operations, the third 7 sorting operations, and so on.

import java.util.Arrays;

public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        if (arr == null) {
            return;
        }
        for (int i = 0; i < arr.length - 1; i++) {
            int flag = 0;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j+1]) {
                    int tmp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                    flag  = 1; }}if (flag == 0) {
                break; }}}public static void main(String[] args) {
        int[] arr = {2.1.8.5.9.4.6.7.3};
        System.out.println("Before sorting:");
        System.out.println(Arrays.toString(arr));
        bubbleSort(arr);
        System.out.println("After sorting:"); System.out.println(Arrays.toString(arr)); }}Copy the code

🎨4. Two-dimensional arrays

A two-dimensional array is essentially a one-dimensional array, except that each element is a one-dimensional array.

So we’ve seen that we’re using a reference to point to an array, so a two-dimensional array is actually an array of type reference, and each element in the array is a reference variable, and the reference variable points to another one-dimensional array.

Two-dimensional array definition:


The data type [ ] [ ] Name of the array =   n e w The data type [ The number of rows ] [ The number of columns ]   { Initialize data } Data types [] [] name \ \ array = \ new \ data type \ [rows] [the number of columns] \ \ \} {initialization data

Array name.length;// indicates the number of linesArray name [line number].length;// Indicates the number of columns in a row
Copy the code
public class TestBolg {
    public static void main(String[] args) {
        int[][] arr = new int[3] [3];
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = 8+ i +j; }}for (int i = 0; i < arr.length; i++) { System.out.println(Arrays.toString(arr[i])); }}}Copy the code

Similarly, there are “three dimensional arrays “,” four dimensional arrays “and other more complex arrays.