对象数组
1.对象数组
1.需求:定义一个长度为3的数组,存储3个Person对象,遍历数组,将三个Person对象中的属性值获取出来
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
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 Demo01ObjectArray {
public static void main(String[] args) {
Person[] arr = new Person[3];
Person p1 = new Person("金莲",26);
Person p2 = new Person("涛哥",18);
Person p3 = new Person("张三",20);
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getName()+"..."+arr[i].getAge());
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/1fa2a0bb80f5992ee661c51588176d82.png)
练习1
(1)定义学生类Student
声明姓名和成绩成员变量
(2)测试类ObjectArrayTest的main中创建一个可以装3个学生对象的数组,并且按照学生成绩排序,显示学生信息
public class Student {
private String name;
private int score;
public Student() {
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
public class Demo02ObjectArray {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("金莲",26);
students[1] = new Student("大郎",50);
students[2] = new Student("涛哥",18);
for (int j = 0; j < students.length-1; j++) {
for (int i = 0; i < students.length-1-j; i++) {
if (students[i].getScore()>students[i+1].getScore()){
Student temp = students[i];
students[i] = students[i+1];
students[i+1] = temp;
}
}
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName()+"..."+students[i].getScore());
}
}
}