题目要求
定义一个Person类(name,age,job),初始化Person对象数组,有3个person对象,按照age从小到大进行排序 使用冒泡排序
使用知识点
1. 构造器,构造方法
2.重写toString方法
3.冒泡排序
源码
public class Exercise01 {
/**
* 定义一个Person类(name,age,job),初始化Person对象数组,有3个person对象,
* 按照age从小到大进行排序 使用冒泡排序
*
*/
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Person("刘备",22,"卖草鞋");
people[1] = new Person("张飞",34,"杀猪的");
people[2] = new Person("关羽",18,"卖鞋的");
//排序前的顺序
for (int i = 0; i < people.length; i++) {
// 直接输出一个对象 会默认调用toString方法
System.out.println(people[i]);
}
// 冒泡排序 (从小到大)
//定义一个中间变量 类型必须是Person
Person temp = null;
for (int i = 0; i < people.length - 1; i++) {
for (int j = 0; j <people.length - i - 1 ; j++) {
if(people[j].getAge() > people[j + 1].getAge()) {
temp = people[j];
people[j] = people[j + 1];
people[j + 1] = temp;
}
}
}
System.out.println("======排序后======");
for (int i = 0; i < people.length; i++) {
// 直接输出一个对象 会默认调用toString方法
System.out.println(people[i]);
}
}
}
class Person {
private String name;
private int age;
private String job;
public Person(String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
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 String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", job='" + job + '\'' +
'}';
}
}