The article directories
- Java Basic Syntax (6) – the definition and use of arrays
- Array basic usage
- 1. What is array
- 2. Create an array
- 3. How to define arrays
- 4. Use of arrays
-
- (1) Get the length
- (2) Access the elements in the array
- (3) subscript out of bounds
- (4) Traverse the number group
- 5. Storage of arrays in memory
- Array as a method parameter
- 1. Basic usage
- 2. Understand reference types
-
- (1) Parameters pass built-in types
- (2) Parameter pass array type
- 3. Know the null
- 4. Initial understanding of JVM memory partition
- Array as a method return value
- Array exercises
-
- 1. Array to string
- 2. Array copy
- 3. Find the largest element in the array
- 4. Average the elements in the array
- 5. Find the specified element in the array.
- 6. Find the specified element in the array (binary search)
- 7. Check the array orderliness
- 8. Array sort (bubble sort)
- 9. Array reverse order
- 5. Two-dimensional arrays
-
- Regular two-dimensional arrays
- (1) The definition of two-dimensional array
- (2) Two-dimensional arrays in memory
- (3) Printing of two-dimensional array
- An irregular two-dimensional array
- Definition of an irregular two-dimensional array in Java
- (1) The definition of irregular two-dimensional array
- (2) Two-dimensional arrays in memory
- (3) Printing method
- Finished!
This content introduces the outline
\
Following up from the previous post on Java Basic Syntax (5) – Using methods \
Java Basic Syntax (6) – the definition and use of arrays
\
Array basic usage
\
1. What is array
\
Arrays essentially allow us to “batch” create variables of the same type.
\
Such as:
If you want to represent two data, create two variables int a; int b
int a = 10;
int b = 20;
Copy the code
If you need to represent five data, you can create five variables int a1; int a2; int a3; int a4; int a5;
int a1 = 10;
int a2 = 20;
int a3 = 30;
int a4 = 40;
int a5 = 50;
Copy the code
But if you need to represent 10,000 data, you can’t create 10,000 variables. This is where we need to use arrays to help us batch create.
int[] array = {10.20.30.40.50};
Copy the code
This is an integer array.
Note: In Java, the variables contained in arrays must be of the same type.
\
2. Create an array
The basic grammar
In the example above, we create an array of type int [] and hold five integers. Explains the use of array creation, Java array creation and C language is very similar, but there are differences.
\
C language version array creation:
int arr[5] = {1.2.3.4.5};
Copy the code
Java version array creation:
int[] arr = {1.2.3.4.5};
Copy the code
\
We can see the difference between the two ways of writing it. In Java, you must [] and data type next to each other.
Array data is stored consecutively in memory. Continue with the above code as an example:
\
Each element of the array has a subscript, and the subscript -> starts at 0, and we’re going to find some data in the array by using the subscript of the array.
\
Note:
An array is also called a collection of data of the same type!
The subscript starts at position 0.
\
3. How to define arrays
\
Definition Method 1
So the code that we wrote above is defining and initializing an array.
This way you just define an array. So that’s the first way we define an array. And the default size of the array so defined is 0.
\
Definition Method 2
This is also defining an array, but the array definition allocates a block of memory to the array with the new keyword, which can hold 10 data.
Int [10] Contiguous memory space allocated.
At this point, we haven’t initialized array yet, so the default value for array is 0.
\
Definition Method 3
In Java, the [] on the left of = cannot be filled with numbers after initialization, and the [] on the right of = can only be given in definition 2.
\
In the definition method three
To summarize three ways to define arrays:
int[] array1 = {1.2.3.4.5}; / / define a
int[] array2 = new int[10]; / / definition 2
int[] array3 = new int[] {1.2.3.4.5}; / / define three
Copy the code
Of the three, the most common way to define an array in Java is method 1.
\
4. Use of arrays
\
(1) Get the length
\
Matters needing attention
- Arr. Length is the member access operator. This is often used in object orientation
Code examples:
public static void main(String[] args) {
int[] array = {1.2.3.4.5};
System.out.println(array.length);
}
Copy the code
Compile result:
\
(2) Access the elements in the array
\
Array access:
\
Matters needing attention:
- Fetches array elements using []. Note that subscripts start at 0
- The [] operation can be used to both read and modify data.
- A subscript access operation cannot exceed the valid range [0, length]. If it does, an out-of-bounds subscript exception will occur
Code examples:
public static void main(String[] args) {
int[] array = {1.2.3.4.5};
// Get the number of elements in the array
//System.out.println(array.length);
// Access the elements in the array
System.out.println(array[1]); // Result: 2
System.out.println(array[2]); // Result: 3
// Modify the elements in the array
array[2] = 100;
System.out.println(array[2]); // Result: 100
}
Copy the code
Compile result:
\
(3) subscript out of bounds
\
Array subscripts start at 0 and range is [0,arr.length), the range between closed and open, or [0,arr. length-1].
If we take the value of the subscript out of the range of the array…
\
As shown below.
public static void main(String[] args) {
int[] arr = {1.2.3.4.5.6};
System.out.println(arr[100]);
}
Copy the code
Compile result:
\
(4) Traverse the number group
\
“Traversal” means that all elements in the array are accessed once, without missing a single element. A loop statement is usually needed
\
1. Traversal method (I) —–for loop
public static void main(String[] args) {
int[] arr = {1.2.3};
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }}Copy the code
Compile result:
As you can see, we use the for loop to iterate through and print out the elements in the array.
\
2. Traversal (2) —->for-each
For-each is another use of the for loop. Can be more convenient to complete the array traversal. Loop conditions and update statement errors can be avoided.
Basic use of for-each
Code examples:
public static void main(String[] args) {
int[] arr = {1.2.3.4.5};
for (int x:arr) {
System.out.print(x+""); }}Copy the code
Compile result:
Principle of for-each traversal
Iterate through every element in the array, take every element out, assign it to x, and print x until all elements in the array are iterated.
Now that we’re done with the two traversal methods, what’s the difference between a for loop and a for-each loop?
A for-loop can get an array index, but for-each can’t get an array index, so for-each can only iterate through the array, not modify or manipulate the array elements.
\
3. Traversal (3) — use the utility class to operate the array to print the array
Arrays is a utility class for manipulating Java Arrays, and you can do all kinds of things with Arrays that you just can’t do.
For example, if we want to print Arrays, we would do it with for-loops or for-each, but we could also print with the Arrays utility class.
Through the JDK tool documentation, we found the corresponding tool class.
Ok, we do the following on the ARR array:
public static void main(String[] args) {
int[] arr = {1.2.3.4.5};
System.out.println(Arrays.toString(arr));
}
Copy the code
Editing results:
\
5. Storage of arrays in memory
\
We’ve covered memory partitioning in Java very briefly in previous posts. Now that we know about the array reference type, how is it stored in memory?
\
Let’s start with a quick review of the Java memory area
We know that local variables are stored on the Java virtual machine stack, while array data is stored on the heap. Array data has a specific address on the heap, and array variables are actually stored on the address of the group of data, and the variable on the stack finds the data on the heap according to that address.
\
The storage of arrays is shown below:
Note:
The figure above shows the address in the heap that arR points to. This address is not a real address, it is obtained by the formal hash of the address. But we can treat it as a real address, because it’s also unique.
So why hash real addresses?
This is the security of Java, do not easily expose their own data address.
\
Array as a method parameter
\
1. Basic usage
\
Code example: Print the contents of an array
public static void main(String[] args) {
int[] arr = {1.2.3};
printArray(arr);
}
public static void printArray(int[] a) {
for (intx : a) { System.out.println(x); }}Copy the code
In this code
1. Int [] arr is an argument to a function.
2. If you need to obtain the array length, you can also use a.length
\
2. Understand reference types
\
In our last blog post on using methods, we looked at a specific case of using methods to exchange two variables. Now let’s go back.
\
(1) Parameters pass built-in types
\
\
We swap variables with built-in types as arguments, but the final compilation does not swap the two variables.
Why is that?
Swap the value of the parameter without affecting the value of the argument.
\
(2) Parameter pass array type
\
We use an array as a parameter to exchange variables. After compiling and running, we found that the values of two variables were successfully exchanged. The array name arr is a reference. When passing a parameter, it is passed by reference.
So why can a reference type operate on a parameter and on an argument?
Let’s start with memory
Above we introduced the memory storage of arrays,
We can see that array, which is a variable on the stack, actually holds the address of the data in the heap, and when we pass an arR array as a parameter to a method, we pass in the address of the data in the heap, and inside the method, we can use that address to find the data in the heap and modify the data, In this way, the parameter changes the operation of the argument.
\
\
Conclusion:
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 (which can be long and expensive).
\
3. Know the null
\
The 0 value of the reference type is null.
\
What does it mean when we assign null to the reference type arr?
\
The reference to arR does not point to any object.
\
When we run this code, the result is null, not the value 0.
\
\
So let’s look at another problem
After we assign null to arR, what is the length of the ARR array?
We’re guessing maybe 0, so let’s run the code.
The running results are as follows:
\
At this point, the editor reported an error, error type: null pointer exception.
Well, at this point we know that null assigns arR, and arR doesn’t point to any array objects, and it doesn’t have any memory space on the heap, so we can’t figure out its length.
\
Conclusion:
Null. An error occurs with a null pointer exception for anything.
Rule of thumb: Whenever such an exception occurs in the future, this reference must be null.
\
4. Initial understanding of JVM memory partition
\
A residence hall is divided into several different areas: freshmen, sophomores… Computer science students, communications students…
\
Memory is similar in that the large corridor is divided into sections, each containing different data.
The MEMORY of the JVM is divided into several regions, as shown:
\
Program Counter (PC Register):
Just a small space that holds the address of the next instruction to be executed.
JVM Stack:
The point is to store local variables (as well as other information). This is where we just created a reference to a storage address like int[] arr.
Native Method Stack
The local method stack is similar to the virtual machine stack. It’s just that the saved content is a local variable of the Native method. In some versions of JVM implementations (such as HotSpot), the local method stack and the virtual machine stack work together.
The Heap (Heap) :
The maximum memory area managed by the JVM. Objects created with new are stored on the heap (for example, new int[]{1, 2, 3})
Method Area:
Used to store information about classes that have been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, and so on. This is where the bytecode compiled by the method is stored.
Runtime Constant Pool
Is part of the method area that holds literal (string constants) and symbolic references. (note that as of JDK1.7, the runtime constant pool is on the heap.)
As for the above division, we will gradually understand it as we learn later. Here we focus on understanding the virtual machine stack and heap.
1. Local variables and references are stored on the stack, and new objects are stored on the heap.
2. The heap space is large and the stack space is small.
3. A heap is one shared by the entire JVM and one stack per thread (multiple stacks may exist in a Java program).
\
Array as a method return value
\
Code examples:
public static void main(String[] args) {
int[] arr = {1.2.3};
transform(arr);
printArray(arr);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }}public static void transform(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2; }}Copy the code
\
This code works, but it breaks the original array. Sometimes we don’t want to destroy the original array, so we need to create a new array inside the method and return it from the method.
\
Modified code:
public static void main(String[] args) {
int[] arr = {1.2.3};
int[] output = transform(arr);
printArray(output);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }}public static int[] transform(int[] arr) {
int[] ret = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
ret[i] = arr[i] * 2;
}
return ret;
}
Copy the code
That way, I won’t break the original array.
In addition, since the array is a reference type, only the first address of the array is returned to the function caller, without copying the contents of the array, which is more efficient.
\
Array exercises
\
1. Array to string
\
Requirements:
Implement a method toString that converts an array of integers to a string.
For example, the array {1, 2, 3} returns the string “[1, 2, 3]”, noting the position and number of commas.
public static String mytoString(int[] arr){
String ret = "[";
for (int i = 0; i <arr.length ; i++) {
if(i! =arr.length-1){
ret+=arr[i]+",";
}else if(i==arr.length-1){
ret+=arr[i]+"]"; }}return ret;
}
public static void main3(String[] args) {
int[] arr ={1.5.6.78.7.87.8.5.45.4.12.12};
//System.out.println(Arrays.toString(arr));
System.out.println(mytoString(arr));
}
Copy the code
\
2. Array copy
\
How to copy an array
\
1. For cyclic copy
// Array copy
public static void main(String[] args) {
int[] arr = {1.2.3.4.5};
int[] copy = new int[arr.length];
for (int i = 0; i <arr.length ; i++) {
copy[i] = arr[i];
}
System.out.println(Arrays.toString(copy));
}
Copy the code
In this way, we first create a new array copy of the same length as arR, and then assign the contents of the ARR array to the copy array through the for loop to achieve the final effect of the array copy.
\
2.Arrays utility classes
1. CopyOf ()
Let’s take a look at the use of the copy tool through the JKD tool documentation
Function: Copies the specified array, truncated or populated (if necessary) with zero so that the copy has the specified length.
Take a look at an implementation of the copyOf method in Java
Array.copyof () returns an int []. The first argument is the original array and the second argument is the length of the new array. The details are as follows…
(2) copyOfRange ()
Let’s start with the JDK documentation to see what the utility class can do
\
Function: Copies the specified range of the specified array into the new array.
Take a look at an implementation of the copyof method in Java
\
\
The return type of copyOfRange method is int [], the first parameter is the original array, the second and third parameters are to copy the original array data subscript, must remember is left closed right open interval, [from, to).
\
Code sample
\
3.System.arraycopy
System. Arraycopy is a native method. It is a native method.
\
Local method
1. Run on the local method stack
2. The bottom layer is implemented by C/C++ code
\
Arraycopy returns no value. The first argument is the original array (the array to be copied), the second argument is the index of the original array to be copied, the third argument is the index of the destination array, the fourth argument is the index of the destination array, and the fifth array is the length to be copied.
\
Code examples:
Note:
\
Arraycopy – The length of the array to be copied. This data cannot exceed the length of the original array, otherwise the editor will report an error: The array is out of bounds.
\
- Array name. clone —-> Generates a copy of the current array
\
Generates a copy of the current array.
\
Code examples:
\
3. Find the largest element in the array
\
Topic content:
Given an array of integers, find the largest element in it.
Code implementation:
public static int findMax(int[] arr){
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i] > max) { max = arr[i]; }}return max;
}
public static void main(String[] args) {
int[] arr={10.20.900.40.100.500};
int ret = findMax(arr);
System.out.println(ret);
}
Copy the code
\
4. Average the elements in the array
\
The subject content
Given an array of integers, take the average
Code implementation:
public static double aver(int[] arr){
int sum = 0;
for (int i = 0; i <arr.length ; i++) {
sum += arr[i];
}
double average = (sum*1.0)/arr.length;
return average;
}
public static void main(String[] args) {
int[] arr = {1.2.8.4.5};
double ret = aver(arr);
System.out.println(ret);
}
Copy the code
Note:
Finally, when calculating the average in aver method, sum should remember sum * 1.0, so that the average calculated is double type data.
\
5. Find the specified element in the array.
\
The subject content
Given an array and an element, find the position of that element in the array.
Code implementation
public static int toFind(int[] arr,int key){
for (int i = 0; i <arr.length ; i++) {
if(key==arr[i])
return i;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1.2.3.4.5};
System.out.println(toFind(arr, 3));
}
Copy the code
\
6. Find the specified element in the array (binary search)
\
For ordered arrays, a more efficient binary lookup can be used.
What is an ordered array?
Order is divided into ascending order and descending order, such as 1, 2, 3, and 4. Ascending order is called ascending order. For example, 4, 3, 2, 1 are in descending order.
Taking an ascending array as an example, the idea of binary search is to take the middle element first and see if the value to be found is larger or smaller than the middle element. If it’s small, look to the left; Otherwise, look to the right.
Code implementation:
public static int binarySearch(int[] arr,int key){
int i = 0;
int j = arr.length-1;
while(i<=j){
int mid = (i+j)/2;
if(arr[mid]==key){
return mid;
}else if(arr[mid]>key){
j=mid-1;
}else if(arr[mid]<key){
i=mid+1; }}// The number to look for was not found when it jumped out of the loop, returning -1 (cannot be array index value)
return -1;
}
public static void main2(String[] args) {
int[] arr = {1.2.3.4.5.6.77.9};
int ret = binarySearch(arr,1);
System.out.println("The subscript to find the number is+ret);
}
Copy the code
\
The idea of binary search can be found in my previous blog – ordered array to find a specific number n (binary search) for details.
\
7. Check the array orderliness
\
The subject content
Given an array of integers, determine whether the array is ordered (ascending)
Code implementation:
public static boolean isSorted(int[] array){
if(array==null) {return false;
}
for (int i = 0; i <array.length-1 ; i++) {
if(array[i+1]<array[i]){
return false; }}return true;
}
public static void main1(String[] args) {
int[] array = null;
System.out.println(isSorted(array));
}
Copy the code
Note:
Remember to check if the array passed in is null, and return false if the arR array passed in is null.
\
8. Array sort (bubble sort)
\
The subject content
Given an array, sort the array in ascending (descending) order.
Algorithm ideas
Each time you try to find the smallest (or largest) element in the current range to sort, place it at the front (or back) of the array.
Code implementation:
public static void main1(String[] args) {
int[] array = {10.51.20.14.64.54};
bubbleSort(array);
System.out.println(Arrays.toString(array));
}
public static void bubbleSort(int[] array){
boolean flg = false;
for (int i = 0; i <array.length-1 ; i++) {
for(int j = 0; j<array.length-1-i; j++){if(array[j]>array[j+1]) {int tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
flg= true; }}if(! flg)break; }}Copy the code
\
Bubbling sort can be explained in detail in my previous blog – bubbling sort sorting algorithm view, here is not more.
\
9. Array reverse order
\
The subject content
Given an array, arrange the elements in reverse order.
Train of thought
Set two subscripts to refer to the first element and the last element. Swap elements in two positions.
Then let the first index increment and the second index decrement, and the cycle continues
Code implementation:
public static void reverse(int[] arr){
int left =0;
int right =arr.length-1;
while(left<=right){
inttmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; }}public static void main(String[] args) {
int[] arr= {1.2.3.4.5.6.7};
reverse(arr);
System.out.println(Arrays.toString(arr));
}
Copy the code
\
5. Two-dimensional arrays
\
A two-dimensional array is essentially a one-dimensional array, except that each element is a one-dimensional array.
\
Regular two-dimensional arrays
\
(1) The definition of two-dimensional array
(2) Two-dimensional arrays in memory
\
Take int [2][3] above as an example
int[] [] = {{1.2.3}, {4.5.6}};
Copy the code
\
We’ve already said that a two-dimensional array is essentially a special one-dimensional array.
Each row of the array arr [0] and arr [1] form a one-dimensional array, with each row holding the address pointing to each column of data.
Each column is also a single one-dimensional array pointing to each data in the heap.
\
(3) Printing of two-dimensional array
\
Arr. Length is the number of rows, and arr [I]. Length is the number of columns.
\
- For loop print
We print this two-dimensional data in a for loop.
\
Code examples:
public static void main(String[] args) {
int[][] arr = {{1.2.3}, {4.5.6}};
for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j <arr[i].length ; j++) {
System.out.print(arr[i][j]+""); } System.out.println(); }}Copy the code
Print result:
\
- For-each printing
Example code if we print with for-each:
public static void main(String[] args) {
int[][] arr = {{1.2.3}, {4.5.6}};
for (int[] array:arr) {
for (int x:array) {
System.out.print(x+""); } System.out.println(); }}Copy the code
The print result is as follows:
\
- The Arrays utility class prints
In a one-dimensional array, we want to convert the array to a string print using Arrays.tostring (). So what’s the utility class for converting a two-dimensional array to a string?
If we print with arrays.tostring ()
\
The result prints the contents of the array represented by the ARR row — the address of the one-dimensional array represented by the column. It’s obvious that arrays.tostring () doesn’t print out the entire contents of a two-dimensional array.
\
We searched JDK documentation and found the deepToString () utility class.
Function: Returns a string representation of the depth content of a specified array.
We print with deepToString ()…
The results are as follows:
\
Successfully printed the contents of a two-dimensional array.
DeepToString () correctly prints all the data in a two-dimensional array.
\
An irregular two-dimensional array
\
In C, when we define a two-dimensional array we can define only the columns, not the rows.
C language array definition
int[] [2] = {1.2.3.4.5.6.7};
Copy the code
In Java, we can only define rows, not columns.
int[][] arr = new int[2] [];Copy the code
\
Definition of an irregular two-dimensional array in Java
\
What is an irregular two-dimensional array?
In the previous rule’s two-dimensional array, each row has the same number of data and the same number of columns. In an irregular two-dimensional array, we specify the number of rows, the number of columns is up to us, the number of columns in each row is up to us.
\
(1) The definition of irregular two-dimensional array
public static void main(String[] args) {
int[][] arr = new int[2] []; arr[0] = new int[] {1.2.3};
arr[1] = new int[] {4.5};
System.out.println(Arrays.deepToString(arr));
}
Copy the code
Compile result:
First we specify a two-dimensional array with two rows
int [ ] [ ] arr = new int [2] [ ];
We ourselves specify how many columns there are in each row of the array.
Arr [0] = new int [] {1,2,3} arr [1] = new int [] {4,5};
This is the definition of an irregular two-dimensional array.
\
(2) Two-dimensional arrays in memory
Basically the same as regular two-dimensional array memory storage.
\
(3) Printing method
\
An irregular two-dimensional array is printed in the same way as a regular two-dimensional array.
\
\
Finally, similarly, there are more complex arrays, such as “three-dimensional arrays” and “four-dimensional arrays,” but only infrequently.
\
Well, this Java basic syntax – array definition and use of knowledge to share here, thank you for your appreciation and attention!!
\
Thank you!!
\