java中数组与对象数组

java数组的声明

java的数组声明不同于c/c++,java不允许在声明数组的方括号内指定数组元素的个数,若声明 int a[5]; 或者int [5] a ; 会导致语法错误。

正确的的数组声明应该是: int [ ] a,b; int a[ ],b[ ]; 特别的,当声明: int [ ] a,b[ ]; 它的等价声明是: int a[ ],b[ ][ ];

为数组分配元素

格式为: 数组名=new 数组类型[元素个数]; 例如:

int a[ ]; a=new int[10];

也可以简写为: int a[ ]=new int[10];

数组长度的计算

使用length;形式为: 数组名.length

int a[ ]=new int[10]; 则a.length=10;

使用变量指定数组元素

与c语言不同的是,java允许使用int型变量指定数组元素的个数,例如:

int size=20; double number[ ]=new double[size];

对象数组

对象数组的声明如下(Student类):

Student [ ] stu; stu=new Student[10];

此时仅仅定义了数组stu有10个元素,且每个元素都是一个Student类型的对象。 但是这些对象目前都还是空对象,在使用数组stu中的对象之前,应该创建数组所包含的对象,如: stu[0]=new Student();

具体例子如下:

class Student {
          
   
	int number;
}
public class Example2_1 {
          
   
	public static void main(String[] args) {
          
   
		Student stu[]=new Student[10];  //创建对象数组stu
		for(int i=0;i<stu.length;i++) {
          
   
			stu[i]=new Student();    //创建Student对象stu[i]
			stu[i].number=50+i;
		}
		for(int i=0;i<stu.length;i++) {
          
   
			System.out.println(stu[i].number);
		}
	}

}
经验分享 程序员 微信小程序 职场和发展