1.一維數組聲明:
一維數組的聲明方式:type var[]; 或type[] var;
聲明數組時不能指定其長度(數組中元素的個數)
2.創建:
Java中使用關鍵字new創建數組對象,格式爲:數組名 = new 數組元素的類型 [數組元素的個數]
3.初始化:
實例:
TestD.java(動態):
TestD.java(動態):
程序代碼:
1. public class TestD
2. {
3. public static void main(String args[]) {
4. int a[] ;
5. a = new int[3] ;
6. a[0] = 0 ;
7. a[1] = 1 ;
8. a[2] = 2 ;
9. Date days[] ;
10. days = new Date[3] ;
11. days[0] = new Date(2008,4,5) ;
12. days[1] = new Date(2008,2,31) ;
13. days[2] = new Date(2008,4,4) ;
14. }
15. }
16.
17. class Date
18. {
19. int year,month,day ;
20. Date(int year ,int month ,int day) {
21. this.year = year ;
22. this.month = month ;
23. this.day = day ;
24. }
25. }
26.
TestS.java(靜態):
程序代碼:
1. public class TestS
2. {
3. public static void main(String args[]) {
4. int a[] = {0,1,2} ;
5. Time times [] = {new Time(19,42,42),new Time(1,23,54),new Time(5,3,2)} ;
6. }
7. }
8.
9. class Time
10. {
11. int hour,min,sec ;
12. Time(int hour ,int min ,int sec) {
13. this.hour = hour ;
14. this.min = min ;
15. this.sec = sec ;
16. }
17. }
TestDefault.java(默認):
程序代碼:
1. public class TestDefault
2. {
3. public static void main(String args[]) {
4. int a [] = new int[]{0,1,2} ;
5. System.out.println("" + a[1]) ;
6. }
7. }
簡單些即:
4.對象數組例子:(一個Student類,一個測試類TestStudent)
//學生類Student.java
public class Student {
private String name; //學員姓名
private int stuNo; //學員編號
private String hobby; //學員愛好
//set/get 方法,封裝學生屬性
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public class Student {
}
//-------------------------------------------------
//測試類TestStudent
public class TestStudent {
public static void main(String[] args) {
}