JAVA集合
对象数组
对象数组练习
举例:创建一个学生数组,存储三个学生对象并遍历
分析步骤:
A.创建学生类
B.创建学生数组
C.创建学生对象
D.将学生对象储存入学生数组中
E.将学生数组进行遍历
- 创建学生类:
创建类的快捷方法:
1.通过源码自动生成构造方法
2.自动生成getxxx()/setxxx()
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 遍历功能实现
public class StudentDemo {
public static void main(String[] args) {
//创建学生数组
Student[] Student = new Student[3];
//创建学生对象
Student s1 = new Student("曹操",40);
Student s2 = new Student("刘备",41);
Student s3 = new Student("张飞",38);
//把学生对象作为元素赋值给学生数组
Student[0] = s1;
Student[1] = s2;
Student[2] = s3;
//遍历学生数组
for(int i =0;i<Student.length;i++) {
Student s = Student[i];
//System.out.println(s);
System.out.println(s.getName()+"---"+s.getAge());
}
}
}
集合类
集合类概述
1.我们学习面向对象编程方法,则需要对对象进行存储,使用对象数组存储对象时,需要给定数组大小,但在现实生活中,对象的数量是不固定的,我们需要根据情况的不同存储不同数量的对象。
2.此前学习的StringBuilder可以实现该功能,但是StringBuilde只能存储String数据类型的数据,无法满足要求。因此需要有集合类方法对对象进行存储。