我的家園

          我的家園

          Java 之 Array 數(shù)組

          Posted on 2012-04-15 16:37 zljpp 閱讀(142) 評論(0)  編輯  收藏
          Java反射技術(shù)除了可以在運(yùn)行時動態(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)換:強(qiáng)行轉(zhuǎn)換成對等的數(shù)組
          int arrayCast[][][] = (int[][][]) array;
          System.out.println(arrayCast[3][5][10]);
          }

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 翁牛特旗| 弥渡县| 文水县| 岑溪市| 旺苍县| 英山县| 翼城县| 绥宁县| 长武县| 东丽区| 泗水县| 富源县| 翼城县| 南康市| 崇阳县| 来凤县| 安龙县| 广汉市| 汉源县| 胶州市| 北流市| 荆门市| 永新县| 高尔夫| 洱源县| 胶州市| 巴里| 定结县| 井研县| 阿拉善左旗| 宜章县| 迁西县| 尉氏县| 宣化县| 慈利县| 秦安县| 濮阳县| 韩城市| 伊吾县| 克什克腾旗| 隆子县|