package com.Wzg;
import javax.naming.Name;
public class Test01 {
public static void main(String[] args) {
person[] people=new person[3];//创建一个person类的数组
people[0]=new person("jerry",45,"loser");
people[1]=new person("morty",14,"student");
people[2]=new person("rick",66,"scientist");
System.out.println("排序前:");
for(int i=0;i<people.length;i++){
System.out.println(people[i]);//直接输出对象,默认会调用tostring方法,我们已经重写了
}
person tmp=null;//定义一个中间变量,类型必须为person
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()){
tmp=people[j];
people[j]=people[j+1];
people[j+1]=tmp;
}
}
}
System.out.println("排序后:");
for(int i=0;i<people.length;i++){
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 + '\'' +
'}';
}
}
对象数组,根据年龄的值排序(java)
最新推荐文章于 2022-08-17 17:29:27 发布