一、对象数组
1.需求:定义一个长度为3的数组,存储3个person对象,遍历数组,将三个person对象中的属性值获取出来
public class Person {
private String name;
private int age;
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 static void main(String[] args) {
/*
1.定义一个存储int型数据的数组:int[]
2.定义一个Person型的数组:Person[]
*/
//定义数组
Person[] arr = new Person[3];
//创建三个对象
Person p1 = new Person("金莲",27);
Person p2 = new Person("大郎",36);
Person p3 = new Person("张三",18);
//将三个对象保存到数组中
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]); //存的是地址值
System.out.println(arr[i].getAge()+" "+arr[i].getName());
}
}
二、练习
1.定义学生类Student
声明学生姓名和成绩成员变量
2.测试类的main函数中创建一个可以装三个对象的数组,并且按照学生成绩排序,显示学生信息
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 static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("小明",83);
students[1] = new Student("小红",91);
students[2] = new Student("小刚",78);
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[j];
students[j] = temp;
}
}
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName()+" "+students[i].getScore());
}
}