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) {
}