Java 引入集合

*对象数组:可以存储对象的数组
 * 需求:
 *     有5个学生,学生有姓名和年龄,使用对象数组来存储这5个学生,
 *                     然后将5个学生遍历出来(展示所有学生的姓名和年龄)
 * 分析:
 *         1)自定义一个学生类:Student
 *         2)给Student类提供两个私有成员
 *         3)定义一个对象数组专门存储学生类型
 *         4)创建具体的5个学生对象
 *         5)遍历对象数组,输出信息
 * 
 * 数组作为一个容器来存储引用类型,不适合长度变化的需求
 *         集合:

public class ObjectArrayDemo {
	public static void main(String[] args) {
//		3)定义一个对象数组专门存储学生类型
		Student[] students=new Student[5];
//		4)创建具体的5个学生对象
		Student s1=new Student("张三",20);
		Student s2=new Student("张三",25);
		Student s3=new Student("张三",30);
		Student s4=new Student("张三",35);
		Student s5=new Student("张三",40);
//		
		students[0]=s1;
		students[1]=s2;
		students[2]=s3;
		students[3]=s4;
		students[4]=s5;
//		5)遍历对象数组,输出信息
		for(int x=0;x<students.length;x++) {
//			System.out.println(students[x]);
			//声明学生对象
			Student s=students[x];
			System.out.println(s.getName()+"  "+s.getAge());
		}
	}
}
public class CollectionDemo3 {
	public static void main(String[] args) {
		//创建集合对象
		Collection c=new ArrayList();
		//创建五个学生对象
		Student s1=new Student("张三",20);
		Student s2=new Student("张三",25);
		Student s3=new Student("张三",30);
		Student s4=new Student("张三",35);
		Student s5=new Student("张三",40);
		//添加元素
		c.add(s1);
		c.add(s2);
		c.add(s3);
		c.add(s4);
		c.add(s5);
		//Object[] toArray():将集合转成数组
		Object objs[]=c.toArray();//向上转型:Object[] objs=new Student();
		//遍历数组
		for(int x=0;x<objs.length;x++) {
//			System.out.println(objs[x]);
			//通过getXXX()获取成员信息
			Student s=(Student)objs[x];//向下转型
			System.out.println(s.getName()+"  "+s.getAge());
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值