The definition and use of arrays in Java (1)

Basic concepts of arrays

If you are now asked to define 100 integer variables, then if you follow the previous approach, the structure may now be defined as follows:

int i1, i2, i3, ... i100;
But at this time, it would be very troublesome to define in this way, because these variables are not related to each other, that is to say, if there is another request now, asking you to output the contents of these 100 variables, it means Write System.out.println () statement 100 times.
In fact, the so-called array refers to a set of related types of variables, and these variables can be operated in a unified manner. The array itself is a reference data type, so since it is a reference data type, it will actually involve memory allocation, and the definition syntax of the array has the following two types.
Array dynamic initialization:
Declare and open up the array:
Data type [] array name = new data type [length];
data type [] array name = new data type [length];

Distribution for array space development (instantiation)
| Tables | Are |
| ------------- |: -------------?
| Declare array: | array Type array name [] = null; | | | array type [] array name = null; | | open up array space: | array name = new` array type [length]; |
 
Then when the array opens up space, you can use the following operations:
Array access is done by index, namely: "array name [index]", but it should be noted that the index of the array starts from 0, so the index range is 0 ~ array length -1, for example, an array of 3 spaces is opened , So the indexes that can be used are: 0,1,2, if the index range of the array is exceeded when accessed at this time, java.lang.ArrayIndexOutOfBoundsException exception information will be generated;
when our array is dynamically initialized to open up space, the Each element is the default value of the corresponding data type of the array; the
array itself is an ordered collection operation, so the operation of the content of the array is often completed in a circular mode, the array is a limited data collection, so you should use cycle.
There is a way to dynamically obtain the length of an array in Java: array name.length;
Example: Define an int array
public  class ArrayDemo {
     public  static  void main (String args []) {
         int data [] = new  int [ 3 ]; / * Open an array of length 3 * / 
        data [ 0 ] = 10 ; // First Element 
        data [ 1 ] = 20 ; // second element 
        data [ 2 ] = 30 ; // third element 
        for ( int x = 0 ; x <data.length; x ++ ) { 
            System.out .println (data [x]); // Control the index through the loop 
        } 
    } 
} 
——————————————————

 

 

Guess you like

Origin www.cnblogs.com/zxbk-xz/p/12747281.html