Java methods and arrays

method

Methods are collections of statements that together perform a function

Method is an ordered combination of steps to solve a class of problems

Method is contained in a class or object

Methods are created in the program and referenced elsewhere

When designing methods, it is best to keep the atomicity of methods, that is, one method completes one function, which is conducive to later expansion

Try to keep the main () method concise

Definition of method

Modifier return value type method name (parameter type parameter name){

/ / method body (function of the method)

Return return value;

}

Formal parameter: used to define the function

Actual parameters: the parameters passed to him by the actual call

return not only returns the result, but also terminates the method

package com.study.method;

public class MethodDemo1 {
    public static void main(String[] args) {
       int num= min(1,1);
        System.out.println(num);

    }
    public  static int min(int num1,int num2){
        int result=0;
        if(num1==num2){
            System.out.println("num1=num2");
            return 0;//Termination method
        }
        if(num1<num2){
            result=num1;
        }else {
            result=num2;
        }
        return result;
    }
}
//Operation results
num1=num2
0

Java is value passing

Method overload

Overloading is a function with the same function name but different formal parameters in a class

Requirements for heavy load:

Method names must be the same

The parameter list must be different (different number or type, or different parameter arrangement order, etc.)

Methods can return the same or different types

Just different return types are not enough to overload methods

Implementation theory: if the method names are the same, the compiler will match one by one according to the number of parameters, parameter types, etc. of the calling method to select the corresponding method. If the matching fails, the compiler will report an error

Command line parameters
Variable parameters

In the declaration of a method, add an ellipsis (...) after the specified parameter type

Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it

package com.study.method;

public class KeBian {
    public static void main(String[] args) {
        KeBian keBian=new KeBian();//Instantiate object
        keBian.number(1,2,4,5,3);
        keBian.number(new int[]{1,23,4,5,6});//Declaration array
    }
    //Variable transmission parameter
    public void number(int... i){
        int j=0;
       while (i.length>j){//i.length can be obtained
           System.out.print(i[j]+" ");
           j++;
       }
        System.out.println();
    }}
//Operation results
1 2 4 5 3 
1 23 4 5 6 

recursion

Self calling reduces the amount of code in the program, but recursion will occupy a lot of memory. Try not to use recursion

The recursive result consists of two parts:

Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle

Recursive body: when do I need to call my own method

package com.study.method;

public class DiGui {
    public static void main(String[] args) {
        System.out.println(number(5));
    }
    //Recursively find n!
    public static int number(int n){
        if(n==1){//boundary condition 
            return 1;
        }else {
            return n*number(n-1);
        }
    }

}
//Result 120

Java is a stack mechanism, and main () is at the bottom

Array (an ordered collection of data of the same type)

  1. Each data is called an array element, and each array element can access them through a subscript
  2. Array describes the combination of several data of the same type in a certain order
Java uses the new operator to create an array syntax:

dataType arrayName=new dataType[arraySize];//arraySize must be written

package com.study.arrary;

public class ArraryDemo1 {
    public static void main(String[] args) {
        int[] a;//Declaration array
       // int b[];// It can also be written like this, but this is the style of c\c + +
        a=new int[5];//Five data can be stored in the array

        //Array assignment
        for (int i=0;i<a.length;i++){
            a[i]=i+1;
            System.out.print(a[i]+" ");
        }
    }
}
//Operation results 1 2 3 4 5

Memory analysis

Heap: stores new objects and data, which can be shared by all threads without storing other object references (specific values of basic types)

Stack: variables that store basic variable types and reference objects (specific addresses referenced in the heap)

Method area: can be shared by all threads, including static and class variables

Static and dynamic initialization of arrays

 	//Static initialization Creation + assignment
        int[] a={1,2,3,4};

    //Dynamic initialization includes default initialization
        int[] b=new int[5];

Four basic characteristics of arrays

The length is fixed. Once the array is created, the size cannot be changed

Array element types must be the same. Mixed types are not allowed

The elements in the array can be any data type, including basic and reference types

Array variables belong to the reference type, and arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object. The array itself is an object. In Java, the object is in the heap. Therefore, whether the array saves the original type or other object types, the array object itself is in the heap.

Array boundary [0,length-1], if it exceeds the boundary, an error will be reported

ArrayIndexOutBoundsException array index out of bounds exception

Use of arrays
package com.study.arrary;

public class ArrayDemo3 {
    public static void main(String[] args) {
        int[] array={1,2,3,4,5};

        //No subscript is generally used for output, and the subscript of the array cannot be obtained
       /* for (int i:array) {
            System.out.println(i);
        }*/
        int[] reverse=reverseArray(array);
        for (int i:reverse) {
            System.out.print(i+" ");   //Execution result 5 4 3 2 1
        }

    }
        //Invert array
        public  static  int[] reverseArray(int[] a){
            int[] result=new int[a.length];//result is an inverted array with the same length as the inverted array
            for (int i = 0,j=result.length-1; i <a.length ; i++,j--) {
                result[j]=a[i];
            }
           return  result;//The return type is an array type
        }
}

Multidimensional array (2D array)

int[][] array=new int[4][2];

Arrays class

They are static methods modified by static, which can be called directly

package com.study.arrary;

import java.util.Arrays;

public class ArraysDemo1 {
    public static void main(String[] args) {
        //Arrays class
        int[] a={1,23,11231,112,123};
        System.out.println(a);//[I@1b6d3586
        //Output array
        System.out.print(Arrays.toString(a));//[1, 23, 11231, 112, 123]
        //Array sort ascending
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));//[1, 23, 112, 123, 11231]

        //The number between array fill subscripts [1, 3) is 0, including 1 but not 3
        Arrays.fill(a,1,3,0);
        System.out.println(Arrays.toString(a));//[1, 0, 0, 123, 11231]
    }
}

Bubble sorting

package com.study.arrary;
import java.util.Arrays;

public class MaoPaoSort {
    public static void main(String[] args) {
        int[] array={8,11,13,14,5,17};
        int[] sort=sort(array);
        System.out.println(Arrays.toString(sort));//[5, 8, 11, 13, 14, 17]
    }
    //Bubble sorting
    // Compare the sizes of adjacent elements in a set of sequences. If the subsequent elements are smaller than the previous elements, exchange their element positions
    //Each comparison will determine a maximum or minimum value
    public static int[] sort(int[] array){// [11,8,13,14,17,5] inner layer 8 11 13 14 5 17
      int temp=0;

        for (int i = 0; i <array.length-1 ; i++) {
            boolean flag=false;//Reduce meaningless comparisons,
            for (int j =0; j <array.length-1-i ; j++) {//The final position is determined one at a time, so array length-1-i
                if (array[j]>array[j+1]){
                    temp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                    flag=true;
                }
            }
            //If there is no comparison and exchange position in the inner loop, the flag is still false, that is, it indicates order, and then the loop will jump out
            if(flag==false){
                break;
            }

        }
        return array;//Returns a sorted array
    }

}

Sparse array

When there are a large number of 0 or the same elements in the array, a sparse array is used to save the array

Processing method of sparse array:

How many rows and columns are there in the record array? How many different values are there

The elements, rows, columns and values with different values are recorded in a small-scale array, so as to reduce the size of the program

package com.study.arrary;

public class XiShuArray {
    //sparse matrix
    public static void main(String[] args) {
        //1. Create a two-dimensional array
        int[][] arr=new int[11][11];
        arr[1][2]=1;
        arr[2][3]=2;
        for (int[] ints:arr) {
            for (int ouInt:ints) {
                System.out.print(ouInt+"\t");//\t space
            }
            System.out.println();
        }

        //Convert to sparse array
        //Get the number of valid values
        int sum=0;
        for (int i = 0; i <arr.length ; i++) {
            for (int j = 0; j <arr[i].length ; j++) {
                if(arr[i][j]!=0){
                    sum++;
                }
            }
        }
        //Create a sparse array of row and column valid values
        int[][] xiArr=new int[sum+1][3];
        //Original array size
        xiArr[0][0]=11;
        xiArr[0][1]=11;
        xiArr[0][2]=sum;
        //Traversing a two-dimensional array will be non-zero
        int num=0;
        for (int i = 0; i <arr.length ; i++) {
            for (int j = 0; j <arr[i].length ; j++) {
                if(arr[i][j]!=0){
                    num++;
                    xiArr[num][0]=i;//Storage abscissa
                    xiArr[num][1]=j;//Storage ordinate
                    xiArr[num][2]=arr[i][j];//Store data
                }
            }
        }
        //Output sparse array
        for (int[] xiArray:xiArr) {
            for (int xiarr:xiArray) {
                System.out.print(xiarr+"\t");
            }
            System.out.println();
           /*   11 11 2
                1  2  1
                2  3  2  */
        }
        
        
        //Restore sparse array
        //1. Read sparse array
        int[][] huanArr=new int[xiArr[0][0]][xiArr[0][1]];
        //2. Element assignment
        for (int i = 1; i <xiArr.length ; i++) {//Traverse the i-th group of data in turn, so it is xiarr length
            huanArr[xiArr[i][0]][xiArr[i][1]]=xiArr[i][2];
        }// huanArr [row] [column] = element value
        for (int[] huArr:huanArr) {
            for (int huanarr:huArr) {
                System.out.print(huanarr+"\t");
            }
            System.out.println();
        }

    }
}
//Output results
0	0	0	0	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	0	0	0	
0	0	0	2	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	

11	11	2	
1	2	1	
2	3	2	

0	0	0	0	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	0	0	0	
0	0	0	2	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	

Keywords: Java Back-end

Added by Bounty on Thu, 13 Jan 2022 18:41:08 +0200