java_數組聲明、創建、初始化,對象數組

1.一維數組聲明:
一維數組的聲明方式:type var[];type[] var;
聲明數組時不能指定其長度(數組中元素的個數)
2.創建:
Java中使用關鍵字new創建數組對象,格式爲:數組名 = new 數組元素的類型 [數組元素的個數]
3.初始化:
1.動態初始化:數組定義與爲數組分配空間和賦值的操作分開進行;
2.
靜態初始化:在定義數字的同時就爲數組元素分配空間並賦值;
3.
默認初始化:數組是引用類型,它的元素相當於類的成員變量,因此數組分配空間後,每個元素也被按照成員變量的規則被隱士初始化。
實例:
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. }
簡單些即:
int a[]=new int[10];//相當於動態
int b[]={0,1,2,3,4,5};//靜態
int c[]=new int[]{0,1,2,4,5}//默認

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;
}

}
//-------------------------------------------------
//測試類TestStudent
public class TestStudent {
public static void main(String[] args) {
//聲明一個學生對象數組
Student[] stu = new Student[2];

//實例化學生對象xixi
Student xixi = new Student();
xixi.setName("xixi");
xixi.setStuNo(18);
xixi.setHobby("我的愛好是音樂");

//實例化學生對象dada
Student dada = new Student();
dada.setName("dada");
dada.setStuNo(24);
dada.setHobby("我的愛好是H啊");

//將xixi和dada放入學生對象數組
stu[0] = xixi;
stu[1] = dada;
for(int i = 0;i < stu.length;i++){
System.out.println("大家好我是:"+stu[i].getName()+"我的學號是:"+stu[i].getStuNo()+"我的愛好是:"+stu[i].getHobby());
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章