preface
For each high-level language, we inevitably have to learn array related knowledge. Today, follow the author to learn the array creation and related use of java. I believe you will gain something after learning it!
Tip: the following is the main content of this article. The following cases can be used for reference
1, What is an array?
An array is a collection of data that stores a set of the same data type.
Arrays essentially allow us to create variables of the same type in batches.
int[] arr={1,2,3,4,5,6,7};
Like C language, the subscript of array in java starts from 0 and then adds 1. You can find an element in the array through the subscript of the array
2, Array creation
Static initialization:
Data type [] array name = {initialize data}
Dynamic initialization:
Data type [] array name = new array type [] {initialization data};
The code is as follows (example):
public static void main(String[] args) { //Method 1: traditionally define an array and initialize it int[] arr={1,2,3};//int [] is a type. You cannot add anything to [] or an error will be reported //new is not written here, but it is actually an object //Method 2: use new to define an array that is not initialized int[] arr2=new int[3];//new is a java keyword used to instantiate java objects. java arrays are also objects //Object, you can imagine it as a concrete object //The effect of this code is equivalent to int[] arr2={0,0,0} //Method 3: use new to define the array and initialize it int[] arr3=new int[]{1,2,3};//You can't add anything in new int [], [] //In the case of method 3, the compiler will also think that it gives an array with a length of 3 and stores 1, 2 and 3. The effect is the same as that of method 1 }
Effect drawing of method I:
Effect drawing of method 2:
Effect drawing of method 3:
ps1: number of array elements and initialization during static initialization
The format of the data is the same
ps2: int[]arr={1,2,3} can also be written as int arr[]={1,2,3} like C language, but we still recommend writing int[]arr={1,2,3}, which is more convenient to understand. Int [] is an integer array type
3, Use of arrays
1. Calculate array length
In C language, we use sizeof (array name) / sizeof (array element type) to calculate the length of the array, but it is very simple to calculate the length of the array in java. We can directly use the array name. Length
Examples are as follows:
public static void main(String[] args) { int[] arr={1,2,3,4,5,6,7}; System.out.println(arr.length); }
The operation effect is as follows:
2. Access array elements
This is the same as the C language. For example, if you want to access the nth element in the array, you can directly the array name [n-1]. For example, there is a 1 integer array arr={1, 2, 3, 4, 5, 6, 7}, and the subscripts are respectively
0, 1, 2, 3, 4, 5, 6 now I want to access the element 4, just access the third subscript of the array
public static void main(String[] args) { int[] arr={1,2,3,4,5,6,7}; System.out.println(arr[3]); }
Print 4 after running
About array access out of bounds: the access subscript exceeds the allowable access range. For example, arr={1, 2, 3} the subscript range you can access is 0 ~ 2. If you access out of this range, such as arr[-1], an error will be reported here because you have accessed out of bounds. The space given to you is the space from array subscript 0 to 2. You access the place that does not belong to you in front, No one knows what was going on in that space at that time. If you suddenly change that space, it may have serious consequences.
3. Traversal array
1. General for loop
public static void main(String[] args) { int[]arr={1,2,3,4,5,6}; for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+" "); } }
The operation effect is as follows:
2. Enhanced for loop (for each loop)
It is written as follows: for (type name, variable name: array name)
Note: the type here needs to correspond to the array element type
public static void main(String[] args) { int[]arr={1,2,3,4,5,6}; for(int x:arr){ //for defines an integer x to receive each number in the integer array System.out.println(x+" "); } }
The printing effect is as follows:
ps: difference between for loop and for each loop
The for loop can get the subscript, but the for each cannot get the subscript
For example, if you want to find a number and return the subscript, you must use the ordinary for loop. If you just get each element in the array, it must be more convenient for each.
3. Use the java tool class Arrays
Arrays is a tool class for manipulating arrays in java. To use the tool class written by others, we need to open the related package import java.util.Arrays;, Just like calling some functions in C language requires #include < header file >
import java.util.Arrays; public static void main(String[] args) { int []arr={1,2,3,4,5,6,7}; String ret= Arrays.toString(arr); //Arrays.toString(arr) turns an array into a string and returns it, //We use ret of string type to receive System.out.println(ret); //If you find it troublesome to write two lines of code //Directly write System.out.println(Arrays.toString(arr)); it's fine too }
The operation effect is as follows:
4, Array as an argument to the method
1. Basic methods
To learn this knowledge, we need to know how arrays are stored
public static void main(String[] args) { int[] array={1,2,3,4,5,6,7}; }
In the main function, array is a local variable, which is placed in the stack, and {1, 2, 3, 4, 5, 6, 7} is stored in the heap as an object. Then your object will have an address number in the heap. Let's assume that its address number is 0x789, then 0x789 is stored in array. Very similar to the pointer of C language, that is, array is indeed a variable, regardless of the address of an object in the heap. Therefore, we also call arr "reference variable", but after all, we study java, not c language, so we don't discuss pointer dereference and other issues.
array is a reference variable, which is used to point to an object. It should be noted that there are also reference variables that do not point to any object. The code is as follows:
public static void main(String[] args) { int []arr=null; System.out.println(arr.length);//An error will be reported after running - null pointer exception //Because you don't point to any object, how can you talk about length }
2. Understand reference types (key and difficult points)
public static void hs1(int[]array1) { array1=new int[]{11,26,13,4,51,61}; } public static void hs2(int[]array2) { array2[0]=211; } public static void main(String[] args) { int []array={1,2,3,4,5,6}; System.out.println(Arrays.toString(array));//[1, 2, 3, 4, 5, 6] hs1(array); System.out.println(Arrays.toString(array));//[1, 2, 3, 4, 5, 6] hs2(array); System.out.println(Arrays.toString(array));//[211, 2, 3, 4, 5, 6] }
We assume that the object address pointed to by array is 0x123
For hs1, after we enter the hs1 method, array passes the address of the object it points to to array1, where 0x123 is saved. That is to say, when we first enter the hs1 method, array1 also points to the object {1,2,3,4,5,6}
But the following array1=new int[]{11,26,13,4,51,61}; We assign a new object to array1 in the heap. We assume that the address of the new object is 0x456. At this time, array1 points to the new object
It should be noted that array1 here is a formal parameter, which does not affect the argument array. You print the argument array the second time, so you still print [1, 2, 3, 4, 5, 6]
As for hs2, after entering hs2, array passes the address it points to to array2, that is, array2 stores 0x123. Then we find the value 1 with subscript 0 of the object through the reference variable array2, and modify the value 1 to 899
What is the difference between hs2 and hs1? hs2 changes the value of the object pointed to by the reference variable through the reference of the formal parameter, and hs1 changes the object pointed to by the formal parameter. The two are essentially different
Note: a reference can only have one object, or it is "Sea King". Sea King will be warned by the system
Take a code example:
public static void main(String[] args) { int []arr=new int[]{1,2,3,4,5}; arr=new int[]{1}; arr=new int[]{2}; arr=new int[]{3}; System.out.println(Arrays.toString(arr));//Print [3] }
To put it bluntly, You arr are now a young man. At first, the young man had an array object {1,2,3,4,5}, but they broke up; He found another array object {1} and broke up again; Later, I found the array object {2} and broke up. Finally, he found the true love array object {3}. Can you say he's wrong? No, he didn't fall in love with many people at the same time. Isn't that normal? This example can also tell us why the reference variable can find the object he points to. It's normal for a young man to have his girlfriend's contact information.
ps: reference variables are not necessarily on the stack
Whether a variable is on the stack or not is determined by the nature of your variable. If it is a local variable or instance member variable, it may not be on the stack, but they can all reference variables. For example, no matter where you were born, you can get objects, not that only one place has the right to get objects.
5, Array as the return value of the method
Code example: write a method to * 2 all the elements in the array
Method I:
public static void func(int[]array) { for(int i=0;i<array.length;i++) { array[i]*=2; } } public static void main(String[] args) { int []arr={1,2,3}; func(arr); System.out.println(Arrays.toString(arr)); }
The reference variable arr points to the object {1,2,3}. Call the func method. We give the address saved by the argument arr to the formal parameter array, that is, array can also point to the object {1,2,3}. Then we modify the object through the array subscript.
However, this doubling is based on the original array, that is, the original array has been changed
Method 2:
public static int[] func2(int []arr) { int []ret=new int[arr.length]; for(int i=0;i<arr.length;i++) { ret[i]=2*arr[i]; } return ret; } public static void main(String[] args) { int []arr={1,2,3}; int []brr=func2(arr); System.out.println(Arrays.toString(brr)); }
The reference variable arr points to an object {1,2,3}. We call the method func2. The address of the object {1,2,3} is given to the formal parameter arr, then we new an object of the same size as arr and give it to RET, then assign the number * 2 in arr to the RET array, and then return ret.
The schematic diagram is as follows:
This will not change the value of the original array.
The printing effects of method 1 and method 2 are as follows:
6, Write your own ToString function
public static String myToString(int[] arr) { if(arr==null) { return null; //Prevent the passed reference variable from having any object, //Then there is no follow-up. length statement } String str="["; for(int i=0;i<arr.length;i++) { str=str+arr[i]+","; } str=str+"]"; return str; } public static void main(String[] args) { int []arr={1,2,3}; System.out.println(myToString(arr)); }
The operation effect is as follows: