First acquainted with Java array operations

Array is one of the most important data types in the Java language. Arrays can solve the processing of complex data in different development scenarios, can quickly store data, flexibly read, and have efficient addition, deletion, modification, and sorting functions. Speaking of this, we think of the sequence in Python. The related data types include tuples, dictionaries, sets, etc. For Java, array operations may be troublesome, but don't worry, let's take it step by step!

The array provided in the Java language is used to store elements of the same type of fixed size

As for what an array is, I won't say much here. The composition of an array is actually somewhat similar to our Python, with each key corresponding to each value.

Declare array variables

dataType[] arrayRefVar;

Generally data type [] variable names form an array

If it is a multi-dimensional array, we will use multiple brackets to define it; when creating an array, we need to specify the length of the array, otherwise it will be inaccessible.

Note that the length of the array is not the same as the index of the array. If the length of the array is 5, the index should be 0-4. This is something you need to pay attention to.


Create array

arrayRefVar = new dataType[arraySize];
 一、使用 dataType[arraySize] 创建了一个数组。
二、把新创建的数组的引用赋值给变量 arrayRefVar。
dataType[] arrayRefVar = new dataType[arraySize];

It can also be done through such a statement

Exception, you don’t need to indicate the length when creating an array. This is more used

//        这里就没有为a这个数组定义它的长度,我们直接在后面定义数组的数据,自动会为我们分配空间!!
        int [] a=new int[]{
    
    12,1,13,69};

It can also be directly followed by {}

  double[] myList = {
    
    1.9, 2.9, 3.4, 3.5};

This is because we use new to be more beneficial to the health of our programs. New can automatically recycle garbage and release related memory for our computer programs! ! !

package 数组;

public class 数组原理 {
    
    
    public static void main(String[] args) {
    
    
        // 数组大小
        int size = 10;
        // 定义数组
        double[] myList = new double[size];
        myList[0] = 5.6;
        myList[1] = 4.5;
        myList[2] = 3.3;
        myList[3] = 13.2;
        myList[4] = 4.0;
        myList[5] = 34.33;
        myList[6] = 34.0;
        myList[7] = 45.45;
        myList[8] = 99.993;
        myList[9] = 11123;
        // 计算所有元素的总和
        double total = 0;
        for (int i = 0; i < size; i++) {
    
    
            total += myList[i];
        }
        System.out.println("总和为: " + total);
    }
}

Insert picture description hereInsert picture description here

Processing array

Generally, we use foreach to deal with arrays, which is similar to the for loop in Python, but it should be noted that the conditions in foreach can only be unique. This is also a major consideration for Java conditional loops.


public class TestArray {
    
    
   public static void main(String[] args) {
    
    
      double[] myList = {
    
    1.9, 2.9, 3.4, 3.5};
 
      // 打印所有数组元素
      for (int i = 0; i < myList.length; i++) {
    
    
         System.out.println(myList[i] + " ");
      }
      // 计算所有元素的总和
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
    
    
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // 查找最大元素
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
    
    
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

for(type element: array)
{
    
    
    System.out.println(element);
}

Array as a function parameter

Arrays can also be like methods, which can pass parameters, make calls and then output, which can make the program structure more obvious. For example, let's take a look at the complete code below:

package 数组;

public class 数组练习 {
    
    
    public static void printLn(int [] num) {
    
    
        for(int i=0;i<num.length;i++) {
    
    
//            System.out.println(num.length);
//            System.out.println(num);
        }
        for(int x:num){
    
    
            System.out.println(x);
        }
    }

    public static void main(String[] args) {
    
    
        printLn(new int[]{
    
    12,26,56,96});
    }

}

Insert picture description here
Here we have achieved the effect by calling a method we wrote before, and we created a main method to call later. Here we use the foreach loop to achieve, so let’s see the result, then we think about it, if We don't use this loop, just print it directly.

Insert picture description hereFour hash codes are printed here, we don't understand the kind! ! ! ! ! This is the rule and the grammar

Arrays can also be used as the return value of methods (functions), let’s take a look at the code


public static int[] reverse(int[] list) {
    
    
  int[] result = new int[list.length];
 
  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    
    
    result[j] = list[i];
  }
  return result;
}

The above is a reverse function program, let's see how it works in the actual program! ! !

package 数组;

public class 数组返回值 {
    
    

    public static int[] reverse(int[] list) {
    
    
//        这是一个倒序功能!!!!!!
        int[] result = new int[list.length];

        for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    
    
            result[j] = list[i];
        }
        return result;
    }

    public static void main(String[] args) {
    
    
        int a[]=reverse(new int []{
    
    1,2,3,4,6,7,8,9,10});
        System.out.println("数组的长度为:"+a.length);
        for(int x:a){
    
    
            System.out.println(x);
        }
    }

}

Insert picture description here
We have introduced so many programs. We have all found that there can be no more than one class in the same program, but multiple public can be declared for method invocation and writing. This is similar to our Python programming language structure.

Multidimensional Arrays

Multidimensional arrays, like our matrices in linear algebra, have data of multiple dimensions.

A multidimensional array can be regarded as an array of arrays. For example, a two-dimensional array is a special one-dimensional array, each element of which is a one-dimensional array


String str[][] = new String[3][4];


type[][] typeName = new type[typeLength1][typeLength2];

package 数组;

public class 多维数组 {
    
    
    public static void main(String[] args) {
    
    
//        这里是为数组分配空间!
        String [][]x=new String[3][3];
        int [][]x=new int[1][3];
//        x[0]=new String[1];
//        x[0]=new String[2];
//      0,1出的数据为“OK!”
        String a=x[0][1]=new String("ok!");


        System.out.println(a);
    }
}


Starting from the highest dimension, we allocate space for each dimension separately, we can see it as two rows of 0 columns


String s[][] = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");

s[0]=new String[2] and s[1]=new String[3] allocate reference space for the highest dimension, that is, limit the longest length of data that can be saved for the highest dimension, and then each Each array element allocates space separately s0=new String("Good") and other operations.

Arrays 类

Insert picture description here

Anyway, my understanding of multi-dimensional arrays is that we have to treat them as a determinant in disguise, [row] [column], so it is better to understand

Common operations on arrays

The length of the array, we use length to operate, do you still know the length in Python (len).

How to add elements to the array, we use the fill method.


The role of Arrays.toString

The function of Arrays.toString() is to conveniently output the array instead of outputting the elements in the array one by one.

This method is used to convert the array into String type output, the input parameter can be long, float, double, int, boolean, byte, object
type array.


This solves the problem that we need to use for loop traversal before!
Format: First importimport java.util.Arrays;

Arrays.toString(数据名)

Very convenient! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !

        Arrays.fill(intArry,0,3,20);

This is added in sequence, starting with 0 index and ending with 3 index, filled with 20, and the rest with 0 (default)

The length of the array cannot be modified after creation, just like our tuples, so we can use some algorithms to modify it, but there is no specific function to provide modification permissions.

Sort

      升序排序
        Arrays.sort(a);
        System.out.println("排序后"+Arrays.toString(a));

Is it the same as our Python

copy

        int[] b=Arrays.copyOf(a,8);
        System.out.println("复制后"+Arrays.toString(b));

The first parameter is the content to be copied, and the second is the length of the copy

Compare

        System.out.println(Arrays.equals(a,b));

Compare whether the two arrays of ab are the same

All demo codes and effects

package 数组;

import java.util.Arrays;

public class 数组返回值 {
    
    

    public static int[] reverse(int[] list) {
    
    
//        这是一个倒序功能!!!!!!
        int[] result = new int[list.length];

        for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    
    
            result[j] = list[i];
        }
        return result;
    }

    public static void main(String[] args) {
    
    
        int a[]=reverse(new int []{
    
    1,2,3,4,6,7,8,9,10});
        System.out.println("数组的长度为:"+a.length);
        System.out.println(Arrays.toString(a));
//        for(int x:a){
    
    
//            System.out.println(x);
//        升序排序
        Arrays.sort(a);
        System.out.println("排序后"+Arrays.toString(a));
//          复制
        int[] b=Arrays.copyOf(a,8);
        System.out.println("复制后"+Arrays.toString(b));
//          比较
        System.out.println(Arrays.equals(a,b));

//        }
    }

}

Insert picture description here
One word per text

Eternity is right, constant is wrong!

Guess you like

Origin blog.csdn.net/weixin_47723732/article/details/108562255