对象数组排序
定义一个Person类{name,age,job,salary},初始化Person对象数组,有三个person对象, 并分别按照age从大到小、名字长度由小到大、工资从高到低排序,提示,使用冒泡排序
Homework01.java
Homework01 main class
package com.hspedu.homework;
/**
* 定义一个Person类{name,age,job},初始化Person对象数组,有三个person对象,
* 并按照age从大到小进行排序,提示,使用冒泡排序
* Homework01.java
*/
public class Homework01 {
public static void main(String[] args) {
//创建对象数组Person
Person[] people = new Person[3];
people[0] = new Person("jack",12,"pupil",50);
people[1] = new Person("tom",18,"nurse",6000);
people[2] = new Person("Marry",24,"worker",3400);
//输出当前的对象数组
for (int i = 0; i < people.length; i++) {
System.out.println(people[i]);
}
//使用冒泡排序
System.out.println("按照年龄由大到小排序后的效果");
Person temp = null;//临时变量,用于交换
for (int i = 0; i < people.length-1; i++) {
for (int j = 0; j < people.length-1-i; j++) {
if (people[j].getAge()<people[j+1].getAge()){
temp = people[j];
people[j] = people[j+1];
people[j+1] = temp;
}
}
}
for (int i = 0; i < people.length; i++) {
System.out.println(people[i]);
}
System.out.println("按照名字长度由小到大排序后的效果");
for (int i = 0; i < people.length-1; i++) {
for (int j = 0; j < people.length-1-i; j++) {
if (people[j].getName().length() > people[j+1].getName().length()) {
temp = people[j];
people[j] = people[j+1];
people[j+1] = temp;
}
}
}
for (int i = 0; i < people.length; i++) {
System.out.println(people[i]);
}
System.out.println("按照工资从高到低排序后的效果");
for (int i = 0; i < people.length-1; i++) {
for (int j = 0; j < people.length-1-i; j++) {
if (people[j].getSalary() > people[j+1].getSalary()) {
temp = people[j];
people[j] = people[j+1];
people[j+1] = temp;
}
}
}
for (int i = 0; i < people.length; i++) {
System.out.println(people[i]);
}
}
}
Person
package com.hspedu.homework;
class Person {
private String name;
private int age;
private String job;
private double salary;
public Person(String name, int age, String job,double salary) {
this.name = name;
this.age = age;
this.job = job;
this.salary = salary;
}
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;
}
public double getSalary(){
return salary;
}
public void setSalary(double salary){
this.salary = salary;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", job='" + job + '\'' +
", salary=" + salary +'\''+
'}';
}
}
operation result