Thinking: int, initialization of an array

xiaoxiao2021-03-06  125

Example Arrayone:

Import java.util. *; public class arrayone {static random rand = new random (); static int code (int mod) {return math.abs (rand.nextint ())% mod 1; public static void main String [] args) {int [] a; a = new int [PRT ("Length of a =" a.length; for (int i = 0; i

==============

Example ArrayTwo:

Public class arrayclassobj {public static void main (string [] args) {integer [] a = new integer [20]; PRT ("length of a =" a.length; for (int i = 0; i

===

Note, here, when I comment out a [i] = new integer (i); this sentence is still running, the result is, A [0] ~ A [19] is null

Understanding (1):

Integer [] a = new integer [20]; the array has been initialized, and the values ​​of each element in the array are NULL, A is an array object, has generated an instance: a = new integer [20]; Its element is a reference to the Integer object, according to the Java specification, its initial value is null, that is, not pointing to any object, in int [] a = new int [3]; each element in the middle group is 0; understanding (2) ):

Shield off a [i] = new integer (i); what is still executed is the following statement PRT ("a [" i "] =" a [i]); it will put a [i ] Convert to string, then want to add. Because of A [i] = null, and NULL This special thing converted into a string is also "null", so your program is inevitable is a [0] = nulla [1 ] = nulla [2] = null ..., of course, you change A [i] in the PRT statement to NULL, the same execution result is the same.

But this is not that your array is ended, and this array is still not initialized. His value is NULL, ie not available. This time calls A [i]. Any method will exceed the method. You should tell the PRT ("a [" i "] =" a [i] .tostring ()); / ** throw an exception after the change, because the basic data type is TSTRING () has been heavy Write, not the basic type to write it yourself, this will pass the address value, but because A [i] is null, so abnormal, specifically, this note is the second article * /

Also want to look at the effect, you can put the above sentence as PRT ("a [" i "] =" new object ()); he outputs the address of Object.toString () converted. So

Only after "generating new Integer objects in initialization", the initialization action is completed:

This sentence is correct. Only this can only use A [i], otherwise it may only be able to execute like PRT, and other probes will be wrong. The reason for run is of course because of that null. Not to say A [I] is available.


New Post(0)