对象数组

对象数组详解

对象数组的定义

1.数组里的元素既可以是基本数据类型,也可以是对象。
2.对象数组的声明和初始化

以Student类为例,创建Student类型的对象数组
(1)对象数组的声明:
      Student[] stus; //和基本数据类型数组是一样的
(2)对象数组的声明并初始化:
      方式一:Student[] stus = {new Student(),newStudent(),...};
      方式二:Student[] stus = new Student[20];//动态初始化,定义了一个学生对象数组,里面可以存储20个学生对象。

对象数组的赋值

定义了一个对象数组,那么该如何为它赋值呢?

我们可以用循环给数组里每个元素赋值。下面以学生对象数组为例。(假设学生对象有两个属性:学号id,int类型 分数score int类型,通过生成随机数赋值,在0100之间)
    Student[] stus = new Student[20];
    for(int i = 0;i<stus.length;i++){ //给数组元素赋值
        stus[i] = new Student();
    }
    //由于没有个每个Student对象的属性赋值,下面给20个Student对象的属性赋值。
    stus[i].id=i+1;//数组是连续的,学号是按1到20排的。
    stus[i].score=(int)((Math.random()*100)+1);//random方法返回的是double类型,而score是int类型,所以这里要强制类型转换。
    

练习

定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。

要求:遍历学生信息并打印出3年级的学生信息。

public class Student {
	    int number;
	    int state;
	    int score;
	    public String toString(){  //重写了toString方法,用于输出学生信息。
	        return "学号:"+number+"\t年级:"+state+"\t成绩:"
                +score ;
	    }
	}
public class Test {
	public static void main(String[] args) {
		Student[] stus = new Student[20];
	    for(int i = 0;i< stus.length; i++){
	        stus[i]=new Student();
	        stus[i].number = i + 1;
	        stus[i].state = (int) ((Math.random()*6)+1);
	        stus[i].score=(int)((Math.random()*100)+1);
	    }
	        Test t = new Test();
	        t.print(stus);
	        t.searchState(stus,3);
	   
	   
	    }
	// 以下的非静态方法不能写在Main方法里,但要写在Test类里
	 public void print(Student[] stus){
	    	for(int i = 0;i< stus.length;i++){   //遍历学生数组
		        System.out.println(stus[i]);
		    }

	    }
	 public void searchState(Student[] stus , int state) {
	    	for(int i = 0;i <stus.length;i++) {   //打印三年级学生的信息
		    	if(stus[i].state==3) {
		    		System.out.println(stus[i]);
		    	}
		    }
}
}
输出结果如下:
学号:1	年级:2	成绩:41
学号:2	年级:4	成绩:67
学号:3	年级:2	成绩:95
学号:4	年级:3	成绩:87
学号:5	年级:2	成绩:26
学号:6	年级:3	成绩:85
学号:7	年级:6	成绩:66
学号:8	年级:1	成绩:40
学号:9	年级:6	成绩:2
学号:10	年级:1	成绩:53
学号:11	年级:5	成绩:82
学号:12	年级:4	成绩:48
学号:13	年级:5	成绩:73
学号:14	年级:6	成绩:76
学号:15	年级:6	成绩:18
学号:16	年级:2	成绩:29
学号:17	年级:5	成绩:47
学号:18	年级:3	成绩:20
学号:19	年级:3	成绩:60
学号:20	年级:4	成绩:8
学号:4	年级:3	成绩:87
学号:6	年级:3	成绩:85
学号:18	年级:3	成绩:20
学号:19	年级:3	成绩:60
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值