A[] d = { new A(), new A()};という初期化に対して,
test(d);とすることができる. 配列の要素がオブジェクトの参照型の場合と基本データ型の場合で同じような扱 いが可能である.
// ObjArray.java class A {} public class ObjArray { static void prt(String str, int[] a) { int i=0; System.out.print(str + "["); System.out.print(a.length+"]:{"); if (i<a.length) System.out.print(a[i++]); while (i<a.length) { System.out.print("," + a[i++]); } System.out.println("}"); } static void prt(String str, Object[] a) { int i=0; System.out.print(str + "["); System.out.print(a.length+"]:{"); if (i<a.length) System.out.print(a[i++]); while (i<a.length) { System.out.print("," + a[i++]); } System.out.println("}"); } static void testA() { A[] a; A[] b = new A[3]; A[] c = new A[4]; for(int i = 0; i < c.length; i++) c[i] = new A(); A[] d = { new A(), new A(), new A() }; System.out.println("testA"); prt(" b", b); prt(" c", c); prt(" d", d); a = d; prt(" a", a); a = new A[] {new A(), new A()}; prt(" a", a); } static void testInteger() { Integer[] a; Integer[] b = new Integer[3]; Integer[] c = new Integer[4]; Integer[] d = { new Integer(5), new Integer(7) }; System.out.println("testInteger"); prt(" b", b); prt(" c", c); prt(" d", d); a = d; prt(" a", a); a = new Integer[] { new Integer(1), new Integer(2) }; prt(" a", a); } static void testint() { int[] a; int[] b = new int[5]; int[] c = new int[4]; for(int i = 0; i < c.length; i++) c[i] = i*i; int[] d = { 5, 7}; System.out.println("testint"); prt(" b", b); prt(" c", c); prt(" d", d); a = d; prt(" a", a); a = new int[] { 1, 2 }; prt(" a", a); } public static void main(String[] args) { testA(); testInteger(); testint(); } }出力は以下のようになる.
% java ObjArray testA b[3]:{null,null,null} c[4]:{A@209f4e,A@3ac748,A@7172ea,A@2f6684} d[3]:{A@738798,A@4b222f,A@3169f8} a[3]:{A@738798,A@4b222f,A@3169f8} a[2]:{A@2457b6,A@7a78d3} testInteger b[3]:{null,null,null} c[4]:{null,null,null,null} d[2]:{5,7} a[2]:{5,7} a[2]:{1,2} testint b[5]:{0,0,0,0,0} c[4]:{0,1,4,9} d[2]:{5,7} a[2]:{5,7} a[2]:{1,2}