Java-array Initialization

Source: Internet
Author: User

Array: An Object Sequence or a data sequence of the basic type encapsulated by an identifier name. Array definition method: int [] A1; the compiler cannot specify the size of the array in the above Code. This brings us back to the question of "Reference. All we have now is a reference to the array, and no space is allocated to the array. To create a bucket for an array, you must write an initialization expression. ** For an array, the initialization action can appear anywhere in the code, but you can also use a special initialization expression, which must appear at the place where the array is created. This special Initialization is composed of a pair of values enclosed in curly brackets. In this case, the compiler is responsible for the distribution of buckets (equivalent to using new. For example: int [] a1 = {1, 2, 3, 4, 5}; so why do we need to define an array reference when no array exists (INT [] A1 ;) what about it? In Java, an array can be assigned to another array, so we can: A2 = A1; what we actually do is to copy a reference.

/** * Title:  * Description:  * Company: Augmentum Inc<br> * Copyright: 2008 (c) Thinking in Java<br> * @author: Forest He * @version: 1.0 */package com.augmentum.foresthe;public class Arrays {public static void main(String[] args) {int[] a1 = {1, 2, 3, 4, 5};int[] a2 = a1;for (int i = 0; i < a2.length; i++) { a2[i]++; }for (int i = 0; i < a1.length; i++) { System.out.println(a1[i]); }}}

** What if the number of elements in the array cannot be determined during programming? You can directly use new to create elements in the array. Although the basic type array is created, new can still work (New cannot be used to create a single basic type of data ).

/** * Title:  * Description:  * Company: Augmentum Inc<br> * Copyright: 2008 (c) Thinking in Java<br> * @author: Forest He * @version: 1.0 */package com.augmentum.foresthe;import java.util.Random;public class ArrayNew {public static void main(String[] args) {Random rand = new Random();int[] a1;a1 = new int[rand.nextInt(5)];System.out.println("a1.length = " + a1.length);for (int i = 0; i < a1.length; i++) { a1[i] = rand.nextInt(100);System.out.println("a1[" + i + "] = " + a1[i]);}}} 
Of course, Arrays can also be initialized while being defined: int [] A = new int [Rand. nextint (20)]; if possible, try to do this. ** If the elements in the array are not of the basic data type, new must be used. Here we encounter a reference problem again, because each element in the created array is a reference.
/** * Title:  * Description:  * Company: Augmentum Inc<br> * Copyright: 2008 (c) Thinking in Java<br> * @author: Forest He * @version: 1.0 */package com.augmentum.foresthe;import java.util.Random;public class ArrayClassObj {static Random rand = new Random();public static void main(String[] args) {Integer[] a1 = new Integer[rand.nextInt(10)];System.out.println("a1.length = " + a1.length);for (int i = 0; i < a1.length; i++) {a1[i] = new Integer(rand.nextInt(1000));System.out.println("a1[" + i + "] = " + a1[i]);}}} 

Here, even after creating an array using new: integer [] a1 = new integer [Rand. nextint (10)]; it is also a reference array, and the initialization process ends only when a new integer object is created and the object is assigned a reference value: a1 [I] = new INTEGER (Rand. nextint (1000); you can also use a list enclosed in curly brackets to initialize an object array. There are two forms:

/*** Title: * Description: * company: Augmentum Inc <br> * copyright: 2008 (c) Thinking in Java <br> * @ Author: Forest he * @ version: 1.0 */package COM. augmentum. foresthe; public class arrayinit {public static void main (string [] ARGs) {/*** implicitly create an array object */Integer [] A = {New INTEGER (1 ), new INTEGER (2), new INTEGER (3 ),}; /*** explicitly create an array object */Integer [] B = new integer [] {New INTEGER (1), new INTEGER (2 ), new INTEGER (3 )};}}
The first form is sometimes useful, but it is very limited because the size of the array is determined during compilation. The last comma in the initialization list is optional (this feature makes it easier to maintain the long list ). The second form provides a convenient syntax to create an object and call a method, which can be used when the number of parameters or type is unknown. Because all classes directly or indirectly inherit from the object class, you can create a method with the object array as the parameter and call it as follows:
/** * Title:  * Description:  * Company: Augmentum Inc<br> * Copyright: 2008 (c) Thinking in Java<br> * @author: Forest He * @version: 1.0 */package com.augmentum.foresthe;class A { int i; }public class VarArgs {static void print(Object[] obj) {for (int i = 0; i < obj.length; i++) System.out.println(obj[i]);}public static void main(String[] args) {print(new Object[] { new Integer(54), new VarArgs(), new Float(4.3), new Double(7.55) });print(new Object[] { "one", "two", "three", "four" });print(new Object[] { new A(), new A(), new A(), });}} 

You can see that the print () method uses the object array as the parameter, and then traverses the array to print each object. Classes in the standard Java library can output meaningful content, ** but the objects of self-built classes (A and varargs, the printed content is only the name of the class, followed by a @ symbol, and a hexadecimal number (This number represents the heap address of the object ). Therefore, the default action (if the tostring () method is not defined) is to print the class name and object address.

Multi-dimensional array:

/*** Title: * Description: * company: Augmentum Inc <br> * copyright: 2008 (c) Thinking in Java <br> * @ Author: Forest he * @ version: 1.0 */package COM. augmentum. foresthe; import Java. util. random; public class multidimarray {static random Rand = new random (); public static void main (string [] ARGs) {/*** 2-D array with fixed length, each vector */INT [] [] a1 = {1, 2, 3}, {4, 5, 6},} in the array is enclosed in curly brackets },}; for (INT I = 0; I <a1.length; I ++) for (Int J = 0; j <A1 [I]. length; j ++) system. out. println ("A1 [" + I + "] [" + J + "] =" + A1 [I] [J]);/*** 3-D array with fixed length, array allocation is completed at a time */INT [] [] [] a2 = new int [2] [2] [4]; for (INT I = 0; I <a2.length; I ++) for (Int J = 0; j <A2 [I]. length; j ++) for (int K = 0; k <A2 [I] [J]. length; k ++) system. out. println ("A2 [" + I + "] [" + J + "] [" + K + "] =" + A2 [I] [J] [k]); /*** 3-D array with varied-length vectors, the vector used to form a matrix in the array can have any length * arrays of irregular shapes */INT [] [] [] A31 = new int [Rand. nextint (5)] [] []; for (INT I = 0; I <a31.length; I ++) {A31 [I] = new int [Rand. nextint (4)] []; for (Int J = 0; j <A31 [I]. length; j ++) A31 [I] [J] = new int [Rand. nextint (3)] ;}for (INT I = 0; I <a31.length; I ++) for (Int J = 0; j <A31 [I]. length; j ++) for (int K = 0; k <A31 [I] [J]. length; k ++) system. out. println ("A31 [" + I + "] [" + J + "] [" + K + "] =" + A31 [I] [J] [k]); /*** 3-D array with varied-length Vectors * rectangular array */INT [] [] [] A32 = new int [Rand. nextint (5)] [Rand. nextint (4)] [Rand. nextint (3)]; for (INT I = 0; I <a32.length; I ++) for (Int J = 0; j <A32 [I]. length; j ++) for (int K = 0; k <A32 [I] [J]. length; k ++) system. out. println ("A32 [" + I + "] [" + J + "] [" + K + "] =" + A32 [I] [J] [k]); /*** array of nonprimitive objects 1 */Integer [] [] A4 ={{ new INTEGER (1), new INTEGER (2 ),}, {New INTEGER (3), new INTEGER (4) ,}, {New INTEGER (5), new INTEGER (6) ,};for (INT I = 0; I <a4.length; I ++) for (Int J = 0; j <A4 [I]. length; j ++) system. out. println ("A4 [" + I + "] [" + J + "] =" + A4 [I] [J]); /*** array of nonprimitive objects 2 */Integer [] [] A5; A5 = new integer [3] []; for (INT I = 0; I <a5.length; I ++) {A5 [I] = new integer [3]; for (Int J = 0; j <A5 [I]. length; j ++) A5 [I] [J] = new INTEGER (I * j);} For (INT I = 0; I <a5.length; I ++) for (Int J = 0; j <A5 [I]. length; j ++) system. out. println ("A5 [" + I + "] [" + J + "] =" + A5 [I] [J]);}
New things about Arrays: All arrays (whether their elements are objects or basic types) have an inherent member. You can use it to know how many elements are contained in the array, but cannot be modified. This member is length. Similar to C and C ++, Java Array records start with 0th elements, so the maximum number of subscripts that can be used is "length-1 ". If the boundary is exceeded, C and C ++ will "Silently" accept and allow you to access all the memory, resulting in many notorious program errors. Java can protect you from this problem. Once the subscript is passed through the bounds, a runtime error (that is, an exception) will occur ). Of course, every time you access an array, the boundary check method requires overhead in time and code, but this function cannot be disabled. This means that if array access occurs on some key nodes, they may be one of the reasons for low program efficiency. However, for the reason of "Internet security and increasing programmer productivity", Java designers think this trade-off is worthwhile.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.