1. Array
An array is a container that stores a fixed number of data , And the container type is the same .
1.1 To define an array
Format 1 :
type [] Variable name ;
Format two :
type Variable name [];
There is no big difference between the two , But the scope of the latter definition has become wider , In addition to arrays, you can also define type variables , Examples are as follows :
public class ArrayTest1 {
public static void main(String[] args) {
// Declared a a Array
int[] a;
// Declared a x Array and a y Variable
int x[], y;
}
}
1.2 Initialization of an array
Arrays cannot be used directly after definition , Space and elements are not allocated , At this time, you need to initialize the initial value to use . Initialization is divided into static 、 Move two .
- dynamic initialization
data type [] Variable name = new data type [ The length of the array ];
int[] x = new int[10];
- initiate static
data type [] Variable name = new data type []{ Elements 1, Elements 2,...};
data type [] Variable name = { Elements 1, Elements 2,...};
int y = {1, 2, 3};
Both static and dynamic initialization are OK .
Static and dynamic initialization can be one of them , Do not mix .
1.3 Array access
Now we define and initialize the array , Let's use . The use of arrays is to access data through indexes, also known as subscripts , The specific use is as follows :
An array variable [ Indexes ]
int[] x = {1, 2, 3, 4};
int y = x[2];
When getting the contents of the array, you should pay attention to :
- The initial index of the array is 0, The maximum subscript is length minus 1
- When accessing, the subscript must be within the subscript range of the array , Otherwise, an out of bounds exception will be thrown (ArrayIndexOutOfBoundsException)
- When the array is uninitialized ( namely x = null), When accessing array elements , A null pointer exception will be thrown (NullPointerException)
1.4 Array application
Array is the unified management of a kind of data , There are many examples of this in life . For example, the math scores of the whole class , Floating point arrays can be used for unified management , Sort according to the requirements . During the interview , Data sorting is often asked , Then we will describe .
Here is a simple example , Print all grades :
public class ArrayTest2 {
public static void main(String[] args) {
double[] x = {59.5, 60, 77, 145, 95};
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
}
}
In the above example x.length Indicates the length of the obtained array , Usage for ( Array variable name .length)
This chapter ends , For personal learning and introduction to Xiaobai , Bosses do not spray !
Source code 【GitHub】 【 Code cloud 】