💜 Write before 💜
Preface
This blog focuses on the following points
1. Understand the basic concepts of arrays
2. Master the basic usage of arrays
3. Array and method interoperability
4. Familiar with array-related common problems and codes~
🎄 Array Basic Usage
🎅 What is an array
Arrays essentially allow us to "batch" create variables of the same type.
For example:
If you need to represent two data, you can create two variables directly to int a. Int b
If you need to represent five data, you can create five variables, int a1; int a2; int a3; int a4; int a5;
But if you need to represent 10,000 data, you can't create 10,000 variables. Then you need to use arrays to help us create them in batches.
Note: In Java, the array must contain the same type of variable.
🎅 Create Array
Basic Grammar
dynamic initialization
Data type [] array name = new data type [] {initialization data};
If the array is not initialized while it is being created, its size must be specified
Data type [] array name = new data type [number of elements];
initiate static
Data Type [] Array Name = {Initialize Data};
Code Samples
int[] arr = new int[]{1, 2, 3}; int[] arr = new int[3]; int[] arr = {1, 2, 3};
Note: When static initialization occurs, the number of elements in the array and the format of the initialization data are the same.
In fact, arrays can also be written as int arr[] = {1, 2, 3};
This is more similar to C. But it is more recommended to write in the form of int[] arr. int and [] are a whole.
🎅 Use of arrays
Code ex amp le: Get Length & Access Elements
int[] arr = {1, 2, 3}; // Get Array Length System.out.println("length: " + arr.length); // Execution results: 3 // Accessing elements in an array System.out.println(arr[1]); // Execution results: 2 System.out.println(arr[0]); // Execution results: 1 arr[2] = 100; System.out.println(arr[2]); // Execution result: 100
Matters needing attention
1. Array length can be obtained using arr.length. This operation is a member access operator. It is often used later in object-oriented.
2. Use [] to press the subscript on the array element. Note that the subscript counts from 0
3. Use [] operations to both read and modify data.
4. Subscript access operations cannot exceed the valid range [0, length - 1]. If they exceed the valid range, a subscript crossover exception will occur
Code example: Subscript out of bounds
int[] arr = {1, 2, 3}; System.out.println(arr[100]); // results of enforcement Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 at Test.main(Test.java:4)
A java.lang.ArrayIndexOutOfBoundsException exception was thrown. Use arrays with subscripts to guard against crossing bounds.
Code example: traversing arrays
Traversal refers to accessing all elements of an array once without repeating them. Loop statements are usually required together.
int[] arr = {1, 2, 3}; for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } // results of enforcement 1 2 3
Code example: traversing arrays using for-each
int[] arr = {1, 2, 3}; for (int x : arr) { System.out.println(x); } // results of enforcement 1 2 3
for-each is another way to use for loops. It makes it easier to traverse arrays. It avoids looping conditions and incorrect updating statements.
🎄 Array as a parameter to the method
🎅 Basic Usage
Code example: Print array contents
public static void main(String[] args) { int[] arr = {1, 2, 3}; printArray(arr); } public static void printArray(int[] a) { for (int x : a) { System.out.println(x); } } // results of enforcement 1 2 3
In this code
- int[] a is a parameter of a function, and int[] arr is an argument of a function.
- If you need to get the length of the array, you can also use a.length
🎅 Understand reference types (tap on the blackboard!!!)
We know that Java is a purely object-oriented language, and we use objects everywhere when programming in the Java language (Everything is object is mentioned in Thinking in Java)
When a program runs, objects are stored in heap memory, so how do we access them? In C/C++ it is through a pointer, while in Java it is through a reference, which stores the address of the object in heap memory.
Let's start with memory.
How do you understand memory?
Memory refers to the familiar "memory". Memory is intuitively interpreted as a dormitory building. There is a long corridor with many rooms on it. Each room is 1 Byte in size (8 billion if the computer has 8G memory).
Each room has another house number, called an address.
So what is a reference?
What is a reference?
A reference is equivalent to an "alias" and can also be interpreted as a pointer.
Creating a reference is equivalent to creating a small variable that holds an integer representing an address in memory.
Take a closer look at the following image (the reference is actually very similar to the pointer)
Difference between reference and pointer
(1) Type:
References to data elements whose values are addresses, Java encapsulated addresses, can be converted to strings for viewing, or lengths can be viewed without worrying.
A C pointer is a variable that holds addresses. The length is usually a computer word length and can be considered an int.
(2) Memory occupied:
There is no entity and no space when referencing declarations.
The C pointer is only assigned if it is used after being declared. Memory will not be allocated if not used.
(3) Type conversion:
Referenced type conversions may also be unsuccessful, throwing exceptions at runtime or compiling may fail.
The C pointer indicates a memory address, points to memory, and is also an address for the program, but may not refer to an address the program wants.
(4) Initial value:
The initial value of the reference is the java keyword null.
The C pointer is int. If the pointer is not initialized, its value is not fixed, which is dangerous.
(5) Calculation:
References cannot be computed.
The C pointer is int, and it can calculate, such as++ or -, so it is often used instead of array subscripts.
(6) Memory leak:
Java references do not cause memory leaks.
C pointer is very easy to cause memory leaks, so programmers should use it carefully and recycle it in time.
🎅 Know null
null denotes an "empty reference" in Java, which is an invalid reference.
Null acts like NULL (null pointer) in C and represents an invalid memory location. Therefore, no read-write operation can be performed on this memory. Once a read-write operation is attempted, a NullPointerException will be thrown.
Note: There is no memory association between null and address 0 conventions in Java.
🎅 Initial JVM memory region partition (knock on the blackboard!!!)
- Program Counter (PC Register): Just a small space to store the address of the next instruction executed.
- Virtual machine stack (JVM Stack): The focus is on storing local variable tables (and other information, of course). A reference to a storage address like int[] arr that we just created is saved here.
- Native Method Stack: A local method stack acts like a virtual machine stack. Only the contents saved are local variables of the Native method. In some versions of JVM implementations (such as HotSpot), the local method stack and the virtual machine stack are together.
- Heap: The maximum memory area managed by the JVM. Objects created with new are saved on the heap (for example, the previous new int[]{1, 2, 3})
- Method Area: Used to store class information, constants, static variables, code compiled by the instant compiler that has been loaded by the virtual machine. The byte code compiled by the method is saved in this area.
- Runtime Constant Pool: A part of the method area that stores literals (string constants) and symbol references. (Note that the runtime constant pool is on the heap starting with JDK1.7).
Native local method:
JVM is a C++ based program. During the execution of Java programs, it is essential to call some functions provided by C++ to interact with the underlying operating system. Therefore, some functions implemented by C++ are also called in Java development.
The Native method here refers to functions implemented in C++ and then called by Java.
In the figure above, we find that program counters, virtual machine stacks, local method stacks are surrounded by a number of base-brown boxes called Thread (Thread), and there are many copies.
Focus on understanding virtual machine stacks and stacks.
- Local variables and references are saved on the stack, and new objects are saved on the stack.
- The space of the stack is very large and the space of the stack is small.
- A stack is one shared across the JVM, and each thread of the stack has one (there may be multiple stacks in a Java program).
🎅 Array as return value of method
Code example: Write a method that will make every element in the array * 2
// Modify the original array directly class Test { 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; } } }
This code works, but it destroys the original array. Sometimes we don't want to destroy the original array, we need to create a new array inside the method and get it back.
// Return a new array class Test { 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; } }
In this way, the original array will not be destroyed.
Also, since the array is a reference type, it is more efficient to return only the first address of the array to the function caller without copying the contents of the array.
🎄 Array Practice
🎅 Binary Search
public class Binary Search { public static int binarySearch(int []arr, int target) { int left = 0; int right = arr.length-1; while (left <= right) { int mid=(left+right)/2; if (arr[mid]<target){ left = mid+1; } else if (arr[mid]>target){ right = mid-1; } else return mid+1; } System.out.println("No number"); return -1; } public static void main(String[] args) { int target = 8; int arr[] = {1,2,3,4,5,6,7,8}; System.out.println("The number to look for is first"+binarySearch(arr,target)+"individual"); } }
🎅 Bubble sort
import java.util.Arrays; public class Bubble sort { public static int[] bubble(int arr[]) { for (int i = 0; i < arr.length-1; i++){ for (int j = 0; j < arr.length-1-i; j++){ if (arr[j]>arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr; } public static void main(String[] args) { int arr [] = {1,1,4,7,2,4,6,9,2,6,5}; System.out.println(Arrays.toString(bubble(arr))); } }
🎅 Determine if the array is in order
public class Determine if the array is in order { public static boolean judgment(int arr[]) { for (int i = 0; (i+1)<arr.length; i++){ if (arr[i]>arr[i+1]) return false; } return true; } public static void main(String[] args) { int arr1[] = {1,2,3,4}; int arr2[] = {2,1,4,3}; if (judgment(arr1)) System.out.println("arr1"+"order"); else System.out.println("arr1"+"disorder"); if (judgment(arr2)) System.out.println("arr2"+"order"); else System.out.println("arr2"+"disorder"); } }
🎅 Elements that occur only once
public class Numbers that appear only once { public static int Only(int arr[]) { int tmp = 0; for (int i = 0; i < arr.length; i++) { /* When it comes to exclusive or operations, you should know what the nature of exclusive or is. 1. Any number, exclusive or to zero, is an original number 2. Exclusive or to itself, 0 3. Exchange and Joint Laws (the key to solving this problem), if you write the calculation of the whole cycle into a mathematical operation, you will find that you can achieve the requirements of this problem by using them. */ tmp ^= arr[i]; } return tmp; } public static void main(String[] args) { int arr[] = {2,0,0,1,1,2,6}; System.out.println(Only(arr)); } }
🎅 Change the value of the original array
import java.util.*; public class Change the value of the original array element { public static int[] transform(int[]array2) { for (int i = 0; i < array2.length; i++) { array2[i] *=2; } return array2; } public static void main(String[] args) { int [] array1 = {1,2,3,}; System.out.println(Arrays.toString(array1)); System.out.println("×2 Array after change="+ Arrays.toString(transform(array1))); } }
🎅 Array So the Sum of Elements
public class Sum of all elements of an array { public static float sum(int[]array) { int sum = 0; for (int i = 0; i < array.length; i++) sum += array[i]; return sum; } public static void main(String[] args) { int [] array = {1,2,3,}; for (int i = 0; i < array.length; i++) System.out.print(array[i]+" "); System.out.println(); System.out.println("So the sum of the elements="+sum(array)); } }
🎅 Array Copy
import java.util.Arrays; public class Copy of Array { public static int[] copyOf(int []arr1) { int []arr2; arr2 = new int[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } return arr2; } public static void main(String[] args) { int []arr1={1,2,3,4,5}; System.out.println("arr1="+Arrays.toString(arr1)); System.out.println("arr2="+Arrays.toString(copyOf(arr1))); } }
🎅 Array to String
public class Array to String { public static void printString(int[]arr) { String a ="["; for (int i = 0; i < arr.length; i++){ a+=arr[i]; if(i != arr.length -1) a += ","; } a+="]"; System.out.println(a); } public static void main(String[] args) { int arr[] = {1,2,3,4,5}; printString(arr); } }
🎅 Averaging array elements
public class Averaging arrays { public static float avg(int[]array) { float avg; int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } avg = sum / array.length; return avg; } public static void main(String[] args) { int [] array = {1,2,3,}; for (int i = 0; i < array.length; i++) System.out.print(array[i]+" "); System.out.println(); System.out.println("Average="+avg(array)); } }
🎄 2-D Array
Two-dimensional arrays are essentially one-dimensional arrays, but each element is another one-dimensional array.
Basic Grammar
data type[][] Array name = new data type [Number of rows][Number of columns] { Initialize data };
Code Samples
The usage of two-dimensional arrays is not significantly different from that of one-dimensional arrays, so we will not go into any further details.
Note, however, that the arrays in C are aligned to the columns, 0 is auto-filled, and no auto-filled in java, as shown in the following code
import java.util.Arrays; public class test { public static void main(String[] args) { int[][] arr; arr = new int[][]{ {1, 2, 3}, {5, 6, 7, 8}, {9, 10, 11, 12} }; for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { System.out.printf("%d\t", arr[row][col]); } System.out.println(""); }// results of enforcement // 1 2 3 // 5 6 7 8 // 9 10 11 12 } }
🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙
❤ Originality is not easy. If there are any errors, please leave a comment in the comments area and say thanks a lot ❤
❤ If you think the content is good, give it three times in a row. ❤
❤ See a return visit~ ❤
🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙