一維數(shù)組的聲明方式:
type var[]; 或type[] var;
聲明數(shù)組時(shí)不能指定其長度(數(shù)組中元素的個(gè)數(shù)),
Java中使用關(guān)鍵字new創(chuàng)建數(shù)組對(duì)象,格式為:
數(shù)組名 = new 數(shù)組元素的類型 [數(shù)組元素的個(gè)數(shù)]
實(shí)例:
TestNew.java:
程序代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class TestNew { public static void main(String args[]) { int [] s ; int i ; s = new int [ 5 ] ; for (i = 0 ; i < 5 ; i++) { s[i] = i ; } for (i = 4 ; i >= 0 ; i--) { System.out.println( "" + s[i]) ; } } } |
初始化:
1.動(dòng)態(tài)初始化:數(shù)組定義與為數(shù)組分配空間和賦值的操作分開進(jìn)行;
2.靜態(tài)初始化:在定義數(shù)字的同時(shí)就為數(shù)組元素分配空間并賦值;
3.默認(rèn)初始化:數(shù)組是引用類型,它的元素相當(dāng)于類的成員變量,因此數(shù)組分配空間后,每個(gè)元素也被按照成員變量的規(guī)則被隱士初始化。
實(shí)例:
TestD.java(動(dòng)態(tài)):
程序代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public class TestD { public static void main(String args[]) { int a[] ; a = new int [ 3 ] ; a[ 0 ] = 0 ; a[ 1 ] = 1 ; a[ 2 ] = 2 ; Date days[] ; days = new Date[ 3 ] ; days[ 0 ] = new Date( 2008 , 4 , 5 ) ; days[ 1 ] = new Date( 2008 , 2 , 31 ) ; days[ 2 ] = new Date( 2008 , 4 , 4 ) ; } } class Date { int year,month,day ; Date( int year , int month , int day) { this .year = year ; this .month = month ; this .day = day ; } } |
TestS.java(靜態(tài)):
程序代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class TestS { public static void main(String args[]) { int a[] = { 0 , 1 , 2 } ; Time times [] = { new Time( 19 , 42 , 42 ), new Time( 1 , 23 , 54 ), new Time( 5 , 3 , 2 )} ; } } class Time { int hour,min,sec ; Time( int hour , int min , int sec) { this .hour = hour ; this .min = min ; this .sec = sec ; } } |
TestDefault.java(默認(rèn)):
程序代碼:
1
2
3
4
5
6
7
|
public class TestDefault { public static void main(String args[]) { int a [] = new int [ 5 ] ; System.out.println( "" + a[ 3 ]) ; } } |
以上就是Java 數(shù)組聲明,創(chuàng)建,初始化等相關(guān)知識(shí),希望能幫助到您,謝謝大家對(duì)本站的支持!