Java Basics--Array __java

Source: Internet
Author: User
Tags array length
Java Basics--arrays

An array is an essential element in a language that can be used to save and manage multiple variables. For example, if you want to count the scores of three students, you can manually define three variables A, B, and C, and you can write three output statements if you want to output the values of these three variables. However, if you want to manage the grades of all the students in one grade, there may be hundreds of students at this time. If you define a variable manually for each student, there are hundreds of variables in the program. And, if you want to output all the students ' scores, there will be hundreds of output statements. Obviously, such code is very complex and tedious.

Therefore, we need to have a way to make it easier to manage multiple data. In this case, we should use the array. First, the basic operation of the array

Arrays: Defining multiple variables of the same type at once.

The array space must be contiguous in memory.

1, creating an array

int []a or int a[] represents one-dimensional array variable A that defines an int type

A=new Int[3]; Indicates that a memory space with a length of 3 int is allocated

Int[]a=new Int[3]; It can also be written in two parts to define a one-dimensional array of type int and allocate the memory space with a length of 3 int at the same time

2, subscript

Defining an array is a one-time definition of multiple variables of the same type. After you have allocated space for an array, you can use the array. When using arrays, you should use subscripts to represent the elements of an array. For example, a variable with a length of 3 int is assigned, and the 3 int variables can be represented by: a[0], a[1, a[2].

That is, if an array of length n is assigned, the array's subscript range is 0~n-1.

A[0] = 10; Assigning an array of elements

A[1] = 20;

A[2] = 30;

3, traversing the array

Iterate through an array: Each element is accessed in a certain order, without omission, without repetition.

Sample code:

Package P5;
public class testarray{public
	static void Main (String [] args) {
		int[]a;//array defined int []a; int a [];
		A=new int[3];//Initializes variable A, allocates space for arrays, and defines the length of the array
		a[0]=1;
		a[1]=2;
		a[2]=3;//Array's assignment for
		(int i=0;i<3;i++) {//traversal array
		System.out.println (A[i]);}
		}


Run Result:

4, initialization of the array

Array elements can be used without assignment, and the array element has a specific default value

BYTE, short, int, long, four integer types, default value 0

Two decimal types, float and double, with a default value of 0.0

Boolean default value is False

The char default value is also 0

Note that 0 of the char type does not refer to the character ' 0 ', but the encoding is 0.

For an array of object types, the default value is null.


Display initialization

The first form is as follows:

Int[] A = {10, 20, 30};

The feature is that you can only use it while defining an array variable.

The second form of syntax is as follows:

Int[] A = new int[]{10, 20, 30};

Note that in this syntax, there is no number in the square brackets following the new keyword, that is, the array length cannot be specified when explicitly initialized, and the array length is determined by the number of elements that follow.

Package P5;
public class testarray{public
	static void Main (String [] args) {
		int[]a;//array defined int []a; int a [];
		A=new int[3];//Initializes variable A, allocates space for arrays, and defines the length of the array
		a[0]=1;
		a[1]=2;
		a[2]=3;//Array's Assignment
		/*
		int[]a={1,2,3};//Array's display initialization, the array length is determined by the number of elements in parentheses
		//int []a=new int [] (1,2,3);
		int []a=new int [3] (1,2,3); Error!!!
		*
		/for (int i=0;i<3;i++) {//traversal array
		System.out.println (A[i])
		;
	}
}

second, the array in memory representation

The representation of the Java array in memory. Look at the following two lines of code

Int[] A;

A = new int[3];

We combine the code to analyze the representation of the array in memory.

The first line, which defines an array variable A, does not allocate contiguous memory space at this time.

The second line, first executes the new int[3, which allocates a contiguous memory space that can be put into 3 int and therefore 12 bytes. Each byte of this 12 byte has its own memory address, in which, the first byte in 12 bytes, its address is called the "first address" of this block of memory. Assume the first address is 1a2b. The third step, after executing new int[3], was assigned. What is the assignment to the variable a? Notice that the assignment is the first address of the memory. In other words, the array variable holds the first address 1a2b in the array. As shown in the following figure

Three, two-dimensional arrays 1, the basic operation of two-dimensional arrays

Two-dimensional arrays and multidimensional arrays: an array of arrays.

For example, in our daily life in the drawer, we can think that the drawer is used to store multiple items, so the drawer is an array of items. And in a closet, you can store multiple drawers, so we can understand that cabinets are arrays of drawers. Therefore, the cabinet can be understood as "array of arrays", that is: The cabinet is the elements of the drawer, and the drawer itself is an array.

Ⅰ, creating a two-dimensional array

Int[][] A; or int[] a[]; or int a[][];

When you define a two-dimensional array variable, you also do not allocate an array space.

A = new int[3][4];

Allocates memory space for two-dimensional arrays, allocating a two-dimensional array of three rows and four columns

We can look at it this way: the two-dimensional array we allocate is equivalent to a closet with three floors and one drawer on each floor. This drawer is divided into four squares, each of which can put an element. Since the two-dimensional array is an "array of arrays", the "row" of the two-dimensional array, which refers to the two-dimensional array, contains several elements. Because the elements of a two-dimensional array are one-dimensional arrays, a "row" is a two-dimensional array containing several one-dimensional arrays. Columns, then, refer to each of the one-dimensional arrays in a two-dimensional array, each containing several elements.

A[0][2]

element that represents the 2nd column in line No. 0


int [][]a={{1,2,3}{5,6,7}{8,9,10}{11,12,13}};

Display initialization for two-dimensional arrays

Ⅱ, traversing two-dimensional arrays

When traversing a two-dimensional array, you get the row and column two values.

First, the two-dimensional array also has a.length such variables, and using a.length to obtain the length, is the number of two-dimensional array elements, that is, the number of rows, also can be understood as: the number of drawers in the cupboard. and the number of columns is equivalent to each one 1a2b a ... The length of the 1A2B 7-dimensional array can also be understood to be the size of each drawer. For the first drawer, we can use A[i].length to get its length.

Sample code:

Package P5;
public class testarray2{public
	static void Main (String [] args) {
		int [][]a=new int[4][3];//the definition of two-dimensional array variables and allocates memory space for two-dimensional arrays,
		Allocates a two-dimensional array of three rows four columns
		//int [][]a=new int [][3];//error!!!
		int [][]a={{1,2,3},{5,6,7},{8,9,10},{11,12,13}};//two-dimensional array display initialization for
		(int i=0;i<a.length;i++) {//Traverse two-dimensional array for
			(int j=0;j<a[i].length;j++) {
				System.out.print (a[i][j]+ "");
			}
			System.out.println ();}}


Run Result:


2, two-dimensional array of memory representation



For a array, it is also a one-dimensional array, which has a length of 3, that is, a array of three elements. A[0],A[1],A[2] Also records the address of a one-dimensional array. So we call a array "one-dimensional array of one-dimensional arrays", which is a two-dimensional array.

3, irregular array

In addition to ordinary two-dimensional arrays, Java also supports irregular arrays. For example, if a cabinet has three drawers, this three drawer does not necessarily have the same size in each drawer, it is entirely possible that the third drawer is larger, the elements more, and the first drawer is comparatively small.

Int[][] A; To define an array variable

A = new int[3][]; The first dimension is determined, indicating that there are three drawers in the cupboard a = new int[][3]; error!

A[0] = new INT[3]; The upper drawer has three elements.

A[1] = new INT[4]; The next layer has four elements

A[2] = new INT[5]; There are five elements at the bottom.

four, an array of common algorithms 1, the expansion of the array

First, the length of the array space cannot be changed once the allocation is complete. Therefore, we are not able to add new memory space directly behind the space of the existing array. We can increase the length of the array in the following ways:

①, allocating a new array, the length of the new array larger than the original array (such as the length is twice times the original array)

②, copy the data from the original array into the new array.

Package P5;
Import Java.util.Arrays;
public class testarrayexpand{public
	static void main (String []args) {
	int []a={1,2,3,4};//defines array A, and shows initialization a
	int []b=new int[8];//defines array B and allocates memory space for B,
	A=expand (a);
	}
	public static int[] Expand (int[]a) {//extension method 1
		int []b=new int[a.length*2];
		for (int i=0;i<a.length;i++) {
			b[i]=a[i];
		
	}
	return b;
		
	}
	public static int []expand1 (int []a) {//extension method 2
		int []b=new int [a.length*2];
		System.arraycopy (a,0,b,0,a.length);
		return b;
	}
	public static int []expand2 (int []a) {//Extension Method 3 return
		
		arrays.copyof (a,a.length*2);
	}
}

2, bubble sort

In the process of sorting, the adjacent elements are continuously compared and exchanged. In the process of swapping, the large element sinks to the end of the array, and the small element moves toward the beginning of the array; it's like in the water: heavy things go down, and light things go up. Because this sort of arrangement is much like the process of bubbles going up in the water, this sort of sorting is called bubble sort.

Next, let's write the bubble sort code. If you have five elements, you need to loop 4 times, that is, if the length of the array is a.length, you need to do a a.length-1 cycle. Therefore, the outer loop is as follows:

for (int i = 0; i<a.length-1; i++) {
		...
		}

The inner loop is slightly more complex. We let the loop variable of the inner loop be J, and each time we compare it, we compare the two elements of A[j and a[j+1]. So how does J's circulation condition be written?

The 1th cycle, the value of I is 0, because to row to the last, so the maximum value of j+1 is A.length,j is a.length-1;

The 2nd cycle, the value of I is 1,j+1 the maximum value of a.length-1,j is a.length-2;

The 3rd cycle, the value of I is 2,j+1 the maximum value of a.length-2,j is a.length-3;

From the above, we know that the maximum value of each cycle j+1 is a.length-i, and the maximum value of J is a.length-i-1. Therefore, the inner-layer cyclic conditions are as follows:

for (int i = 0; i<a.length-1; i++) {
	for (int j = 0; j<a.length–i-1; j + +) {
		compare a[j] and a[j+1], if A[J] is larger than a[j+1, then pay Value of two elements
		}
	}

Further refinement, the code is

for (int i = 0; i<a.length-1; i++) {for 
		(int j = 0; j<a.length–i-1; j + +) { 
			if (A[j] > A[j+1]) { 
				swap a[j] and Value of A[j+1]}} 
	

How to exchange the value of two variables. Suppose there are two variables a = 5;b=4; to exchange the values of two A and B, what should be done.

If a = B is executed directly, the value of a of 5 is overwritten by the value of B. So, A has the value of B, but B can't get the original value of the A variable. Therefore, in order to exchange the values of two variables, a third variable is required.

First, define a new variable t; then assign the value of a to t:t = A;

Next, assign the value of B to a:a=b. This will overwrite the original value of a, but it doesn't matter, a the original value has been saved in the T variable.

Then, the value of the original a variable saved in the T variable is assigned to B.

Sample code:

Package P5;
public class testarraysort{public
	static void Main (String[]args) {
		int []data={5,4,2,1,3};//defines a one-dimensional array. and show initialization array
		int n=data.length;//define variable n array length, easy to use array length for
		(int i=1;i<n;i++) {//bubble sort must be n-1 times, I represents first bubble sort
			for (int j=0;j< (n-i); j + +) {//inductive summary, starting from 0 Data[j] and data[j+1] compare n-i times
				if (data[j]>data[j+1) {
				int t=data[j ];
				DATA[J]=DATA[J+1];
				DATA[J+1]=T;//DATA[J] and data[j+1] swap location
				}
				
			}	
			
			
		} for
		
		(int i=0;i<data.length;i++) {
			System.out.print (data[i]+ "");/traverse output DATA[I]
		}
		System.out.println ()//NewLine
		
	 	
	}
}
Run Result:


3, select the sort

Selection sorting is a simple and intuitive sort algorithm. It works by selecting the smallest (or largest) element each time from the data element to be sorted, storing it at the start of the sequence until all the data elements to be sorted are finished. Selecting a sort is an unstable sort method (for example, the sequence [5, 5, 3] swaps the first [5] with [3] for the first time, causing the first 5 to move to the second 5 back)

Package P5;
public class testarraysort{public
	static void Main (String[]args) {
		int []data={5,4,2,1,3};//defines a one-dimensional array. and displays the initialization array
		int n=data.length;//defines the variable n as an array length, making it easy to use the length of the arrays for
		(int i=0;i< (n-1); i++) {//select sort for
			(int j=i+1;j <n;j++) {
				if (Data[i]>data[j]) {
					int t=data[i];
					DATA[I]=DATA[J];
					Data[j]=t
			
		}
		
		}} for (int i=0;i<data.length;i++) {
			System.out.print (data[i]+ "");//Traverse output DATA[I]
		}
		System.out.println ();//NewLine
		
	 	
	}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.