標籤:java 數組 初始化 分析
數組是對象:
無論使用哪種類型的數組,數組標示符其實只是一個引用,指向在堆中建立的一個真實對象,這個數組對象用以儲存指向其他對象的引用。
可以作為數組初始化文法的一部分隱式的建立此對象,或者用new運算式顯示的建立。
唯讀成員length是數組對象的一部分(事實上這是唯一一個可以訪問的欄位或方法),表示此數組對象可以儲存多少元素。“[]”文法是訪問數組對象的唯一方式。
初始化數組的各種方式 & 對象數組和基本類型數組的使用:
下例總結了初始化數組的各種方式,也說明,對象數組和基本類型數組在使用上幾乎是相同的;
唯一的區別就是對象數組儲存的是引用,基本類型數組直接儲存基本類型的值。
class BerylliumSphere {private static long counter;// 靜態變數是屬於類的,且唯一。private final long id = counter++;// final變數值不可以被改變public String toString() {return "Sphere " + id;}}public class Main {public static void main(String[] args) {/** * 對象數組 * */BerylliumSphere[] a; // 建立一個對象數組引用BerylliumSphere[] b = new BerylliumSphere[5]; // 建立一個數組對象引用,指向在堆中建立的一個真實對象// 堆中真實數組所有的引用會自動初始化為null// b:[null, null, null, null, null]System.out.println("b:"+Arrays.toString(b));BerylliumSphere[] c = new BerylliumSphere[4];// for (int i = 0; i < c.length; i++) {if (c[i] == null) { // 能夠測試是否為null引用c[i] = new BerylliumSphere();}}// 聚集初始化BerylliumSphere[] d = {new BerylliumSphere(),new BerylliumSphere(),new BerylliumSphere()};// 動態聚集初始化a = new BerylliumSphere[]{new BerylliumSphere(),new BerylliumSphere(),new BerylliumSphere()};/*a.length = 3b.length = 5c.length = 4d.length = 3a.length = 3*/System.out.println("a.length = " + a.length); // length是數組的大小,而不是實際儲存的元素個數System.out.println("b.length = " + b.length);System.out.println("c.length = " + c.length);System.out.println("d.length = " + d.length);a = d;System.out.println("a.length = " + a.length);/** * 基礎資料型別 (Elementary Data Type)數組 * */int[] e; // null 引用int[] f = new int[5]; // 會自動初始化為0System.out.println("f:"+Arrays.toString(f));int[] g = new int[4];for (int i = 0; i < g.length; i++) {g[i] = i*i;}int[] h = {11,47,91};/*f:[0, 0, 0, 0, 0]f:[0, 0, 0, 0, 0]g:[0, 1, 4, 9]h:[11, 47, 91]e:[11, 47, 91]e:[1, 2]*/System.out.println("f:"+Arrays.toString(f));System.out.println("g:"+Arrays.toString(g));System.out.println("h:"+Arrays.toString(h));e = h;System.out.println("e:"+Arrays.toString(e));e = new int[]{1,2};System.out.println("e:"+Arrays.toString(e));}
數組b初始化為指向一個BerylliumSphere引用的數組,但其實並沒有BerylliumSphere對象置入數組中。
然而,仍可以詢問數組的大小,因為b指向一個合法的對象。這樣做有一個小缺點:你無法知道在此數組中確切的有多少元素,
因為length只表示數組能夠容納多少元素。也就是說,length是數組的大小,而不是實際儲存的元素個數。
新產生一個數組對象時,其中所有的引用被自動初始化為null。同樣,基本類型的數組如果是數值型的,就被自動初始化為0,字元型char,自動初始化為0,布爾型為false。
結果:
基本類型數組的工作方式和對象數組一樣,不過基本類型的數組直接儲存基本類型資料的值。
數組之---數組是第一級對象!