javaEE_day04 ☞ java array learning and sorting

Understanding arrays

An array is also a data type, which is itself a reference type.
1. what is an array: a container that stores the same data type

2. features:

Java arrays can store both basic type data and reference type data, as long as all array elements have the same type;
Ordered (subscript, starting from 0);
Once the initialization of the array is completed, the space occupied by the array in memory will be fixed, so the length of the array will not be changed. (attribute length) even if the data of an array element is cleared, the space occupied by it is still reserved and belongs to the array. The length of the array remains unchanged.

Define array

Array name of type [] of data element;
int[] nums;
int nums[];

Array is a variable of reference type. Therefore, when defining a variable with it, it only means that a reference variable (that is, a pointer) has been defined. This reference variable has not pointed to any valid memory. Therefore, the length of the array cannot be specified when defining an array. Moreover, since the definition of array only defines a reference variable and does not point to any valid memory space, there is no memory space to store array elements. Therefore, this array cannot be used. It can only be used after the initialization of the array.

Create array (request memory)

As long as memory space is allocated for the array elements, the array elements have initial values.
There are two ways to initialize an array.

Static initialization: during initialization, the programmer explicitly specifies the initial value of each array element, and the system determines the array length.
Dynamic initialization: during initialization, the programmer only specifies the array length, and the system allocates the initial value for the array elements.

1. static initialization
The syntax format of static initialization is as follows:

arrayName = new type[] {el ementl, element2 , element3 , element4 .. . } 

In addition, static initialization has the following simplified syntax format:

type[] arrayName = {elementl, element2, element3, element4 . . . } 

2. dynamic initialization
The syntax format of dynamic initialization is as follows:

arrayName = new type[length] ;

After array initialization, you can use the array, including assigning values to array elements, accessing array element values, and obtaining array lengths.

Store data

// Assign a value to the first array element of nums 
nums[0]=1;
nums[9]=2;

Use array

// Output the first element of the num array
System.out.println(nums[0]);

for(int i=0;i<nums.length;i++){
    System.out.println(nums[i]);
}

Enhanced for loop (foreach loop)

for(int i : nums){
System.out.println(n);
}

//Array becomes string
Array.toString(nums);

        int nums[];
		nums=new int[10];
		nums[0]=1;
		nums[9]=2;
		//Array becomes string
		System.out.println(Arrays.toString(nums));    //[1, 0, 0, 0, 0, 0, 0, 0, 0, 2]
		for(int i=0;i<nums.length;i++) {
			//Assign values to elements in an array
			nums[i]=90;
			System.out.println(nums[i]);    //The result is 10 90
		}
		//Test whether the elements in the array are really assigned
		System.out.println("aaa"+nums[2]);    //aaa90, so this method can assign values to array elements
		
		for(int n:nums) {
			n=80;
			System.out.println(n);   //The result is 10 80
		}
		System.out.println("Not assigned"+nums[2]);   //Not assigned 0

From the above program, when using foreach to iterate to access array elements, the circular variable in foreach is equivalent to a temporary variable, and the system will assign array elements to this temporary variable in turn. This temporary variable is not an array element, but only saves the values of array elements. Therefore, you cannot use this foreach loop if you want to change the value of an array element.

Use of args array of main method

public static void main(String[] args) {
		//Exercise: sum array elements
		//Integer.parseInt(args[i]);
		int sum=0;
		for(int i=0;i<args.length;i++) {
			int n=Integer.parseInt(args[i]);
			sum+=n;
			System. out .println(n+" ");
		}
		System. out .println("The sum is:"+sum);
		//System. out .println(Arrays.toString(args)); 
	}

give the result as follows

1 
2 
3 
4 
Sum: 10

Copy and expansion of array

Arrays ToString (type[] a): this method converts an array into a string

        int [] a= {1,2,3,4,5};
		int [] b= new int[10];
		//Copy of array
		//b= {1,2,3,0,0......};
		//arraycopy
	    //First parameter: original array
		//Second parameter: the starting position of the original array element
		//Third parameter: target array
	    //Fourth parameter: the starting position of the target array element
		//Fifth parameter: length
	//	System.arraycopy(a, 0, b, 0, 3);
	//	System.out.println(Arrays.toString(b));
		
		//Exercise: b={0,0,3,4,0...}
		System.arraycopy(a, 2, b, 2, 2);
		System.out.println(Arrays.toString(b));

Array expansion (a new array is actually created). See the following figure for details

        //Array expansion (a new array is actually created)
		//copyOf
		//First parameter: original array (copy)
		//Second parameter: length after capacity expansion
		String[] names= {"wolf"};
		names[1]= "Lisi";
		// The index value specified by the access array element is equal to the array length, so the following code will cause an exception at run time 
		System.out.println(names[1]);

If the index value specified when accessing an array element is less than 0, or greater than or equal to the length of the array, the compiler will not make any errors, but an exception occurs at runtime: java Lang.arrayindexoutotboundsexception: n (array index out of bounds exception),

       names=Arrays.copyOf(names, names.length+1);
       names[1]="Lisi";
       //The result is [Zhang San, Li Si]
   System.out.println(Arrays.toString(names));

Memory: heap, stack, method area, local method stack, register
Stack local variable
Stacking objects
Thread garbage collection of jvm

Why is there stack memory and heap memory?
When a method is executed, each method will create its own memory stack, and the variables defined in this method will be put into this memory stack one by one. With the end of the method execution, the memory stack of this method will be destroyed naturally. Therefore, all local variables defined in the method are placed in stack memory; When an object is created in a program, it will be saved to the runtime data area for reuse. This runtime data is heap memory. The object in heap memory will not be destroyed with the end of the method. Even if the object may be referenced by another reference variable after the end of the method, the object will not be destroyed. Only when an object does not have any reference variables to reference it, the system's garbage collector will collect it at the appropriate time.

Tip: when looking at an array, you must regard the array as two parts: one part is array reference, that is, array reference variables defined in the code; The other part is the actual array object. This part is run in the heap memory. Usually, it cannot be accessed directly, but only through the array reference variable.

Sorting of array elements

1. bubble sort
Compare the two, the big one sinks, the small one floats, from small to large

Picture from here.

Example: sort 23, 56, 22, 15
First round sorting:
The results were 23, 22, 15, 56. Exchanged 3 times
The process is as follows

 23,56
     22,56
         15,56        

Second round sorting:
The results are 22, 15, 23, exchanged twice
The process is as follows

 22,23
     15,23

Third round sorting:
The results were 15, 22. Exchanged once

Implemented in Java code:

		int[] num= {23,56,22,15};
		int x;
        //Three rounds of sorting
		for(int i=0;i<3;i++) {
		    //Exchange times
			for(int j=0;j<num.length-1-i;j++) {
				if(num[j]>num[j+1]) {
					x=num[j];
					num[j]=num[j+1];
					num[j+1]=x;
				}
			}
		}
		//The result is [15, 22, 23, 56]
		System.out.println(Arrays.toString(num));

2. Select Sorting:

Implemented in Java code:

        for(int i=0;i<num.length-1;i++) {
			for(int j=i+1;j<num.length;j++) {
				if(num[i]<num[j]) {
					int x=num[i];
					num[i]=num[j];
				}
			}
		}
		System.out.println(Arrays.toString(num));

In addition to the above, the sorting method is arrays Sort (Num); You can also sort.

Two dimensional array

1. statement:
int[][] arrays;
//The first [] represents a row and the second represents a column
int[] arrays[];
int arrays[][];

int[] a[],b;   //a two-dimensional, b one-dimensional Both exclude
int[] c=new int[2];
int [][] d=new int[2][3];
//Only the same data type can be assigned

a=c;    //Two dimensional array assigned to one dimensional array error
b=c;    //ok
a=d;    //error, because a just declares that d points to memory
                     b=d;    //error   ??????
a[0]=c;  //A is two-dimensional, but a[0] represents the first row and is a one-dimensional array
a[0]=d;  //error

2. create:
Arrays=new int[2][3]// 2 rows and 3 columns

3. assignment:
arrays[0][2]=1;
The result is:

0 0 1
0 0 0

Get array elements, using nested loops

//2D array name length is the row of a two-dimensional array
		int[][] nums;
		nums=new int[2][3];
		nums[1][1]=1;
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){
		         System.out.print(nums[i][j]+"\t");
		     }
		    System.out.println();
		}

The result is:

0	0	0	
0	1	0

Other ways to define 2D arrays:

//Other ways to define 2D arrays
		int[][] nums=new int[2][3];
		int[][] nums2= {{1,2,3},{4,5,6}};
		int[][] nums3=new int[][]{{1,2,3},{4,5,6}};

Definition of irregular two-dimensional array

        //int[][] nums=new int[][3];    error
		//int[][] nums=new int[][];   error
		int[][] nums=new int[3][]; //3 lines
		nums[0]=new int[3];
		nums[1]=new int[1];
		nums[2]=new int[5];
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){
		         System.out.print(nums[i][j]+"\t");
		     }
		    System.out.println();
		}

The result is:

0	0	0	
0	
0	0	0	0	0	

Exercises

    //Sum of diagonal lines
	public static void test() {
		int[][] nums=new int[][]{{1,2,3},{1,2,2},{3,2,2}};
		int sum=0;
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){
		    	if(i==j||i+j==2) {
		    		sum+=nums[i][j];
		    	}
		     }
		}
		System.out.print(sum);
	}
	
	//Matrix transpose
	/*
	 * [0][0]  [1][0]
	 * 
	 *  
	 */
	public static void test4() {
		int[][] nums=new int[][]{{1,2,3},{4,5,6}};
		int[][] nums2=new int[3][2];
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[0].length;j++){
		    	nums2[j][i]=nums[i][j];	
		     }
		}
		for(int i=0;i<nums2.length;i++){
		    for(int j=0;j<nums2[i].length;j++){
		         System.out.print(nums2[i][j]+"\t");
		     }
		    System.out.println();
		}
		
	}
	
	//Yanghui triangle
	public static void test3() {
		Scanner sc=new Scanner(System.in);
		System.out.println("input n:");
		int n =sc.nextInt();
		int[][] nums = new int[n][];
		for(int i=0;i<nums.length;i++){
			nums[i]=new int[i+1];
		    for(int j=0;j<nums[i].length;j++){
		    	if(j==0||i==j) {
		    	nums[i][j]=1;
		    	}else {
		    		nums[i][j]=nums[i-1][j-1]+nums[i-1][j];
		    	}
		     }  
		}
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){
		         System.out.print(nums[i][j]+"\t");
		     }
		    System.out.println();
		}
	}

Tags: Java

Posted by freeloader on Mon, 30 May 2022 09:11:50 +0530