我的家園

          我的家園

          Java 之 Array 數(shù)組

          Posted on 2012-04-15 16:37 zljpp 閱讀(143) 評論(0)  編輯  收藏
          Java反射技術(shù)除了可以在運行時動態(tài)地決定要創(chuàng)建什么類型的對象,訪問哪些成員變量,方法,還可以動態(tài)地創(chuàng)建各種不同類型,不同維度的數(shù)組。

          動態(tài)創(chuàng)建數(shù)組的步驟如下:
          1.創(chuàng)建Class對象,通過forName(String)方法指定數(shù)組元素的類型
          2.調(diào)用Array.newInstance(Class, length_of_array)動態(tài)創(chuàng)建數(shù)組

          訪問動態(tài)數(shù)組元素的方法和通常有所不同,它的格式如下所示,注意該方法返回的是一個Object對象
          Array.get(arrayObject, index)

          為動態(tài)數(shù)組元素賦值的方法也和通常的不同,它的格式如下所示, 注意最后的一個參數(shù)必須是Object類型
          Array.set(arrayObject, index, object)

          動態(tài)數(shù)組Array不單可以創(chuàng)建一維數(shù)組,還可以創(chuàng)建多維數(shù)組。步驟如下:
          1.定義一個整形數(shù)組:例如int[] dims= new int{5, 10, 15};指定一個三維數(shù)組
          2.調(diào)用Array.newInstance(Class, dims);創(chuàng)建指定維數(shù)的數(shù)組

          訪問多維動態(tài)數(shù)組的方法和訪問一維數(shù)組的方式?jīng)]有什么大的不同,只不過要分多次來獲取,每次取出的都是一個Object,直至最后一次,賦值也一樣。

          動態(tài)數(shù)組Array可以轉(zhuǎn)化為普通的數(shù)組,例如:
          Array arry = Array.newInstance(Integer.TYPE,5);
          int arrayCast[] = (int[])array;

          【2】示例代碼
          A. 一維數(shù)組:
          public static void main(String args[]) throws Exception {
          Class<?> classType = Class.forName("java.lang.String");
          // 創(chuàng)建一個長度為10的字符串?dāng)?shù)組
          Object array = Array.newInstance(classType, 10);
          // 把索引位置為5的元素設(shè)為"hello"
          Array.set(array, 5, "hello");
          // 獲得索引位置為5的元素的值
          String s = (String) Array.get(array, 5);
          System.out.println(s);
          }

          B. 多維數(shù)組:
          public static void main(String args[]) {
          int[] dims = new int[] { 5, 10, 15 };
          // 創(chuàng)建一個具有指定的組件類型和維度的新數(shù)組。
          Object array = Array.newInstance(Integer.TYPE, dims);

          // 取出三維數(shù)組的第3行,為一個數(shù)組
          Object arrayObj = Array.get(array, 3);
          Class<?> cls = arrayObj.getClass().getComponentType();
          System.out.println(cls);

          // 取出第3行的第5列,為一個數(shù)組
          arrayObj = Array.get(arrayObj, 5);
          // 訪問第3行第5列的第10個元素,為其賦值37
          Array.setInt(arrayObj, 10, 37);

          // 動態(tài)數(shù)組和普通數(shù)組的轉(zhuǎn)換:強行轉(zhuǎn)換成對等的數(shù)組
          int arrayCast[][][] = (int[][][]) array;
          System.out.println(arrayCast[3][5][10]);
          }

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 永新县| 信宜市| 大同县| 海门市| 扬州市| 文山县| 上饶县| 贡觉县| 莎车县| 镶黄旗| 九江县| 岳西县| 娄底市| 咸丰县| 思茅市| 阳江市| 沂源县| 凤台县| 肃南| 安西县| 桃江县| 将乐县| 吉木萨尔县| 菏泽市| 买车| 临洮县| 高州市| 内丘县| 澄迈县| 呼伦贝尔市| 巴马| 获嘉县| 神木县| 邢台市| 枣庄市| 上犹县| 恩施市| 桃源县| 双桥区| 永州市| 佛山市|