1、定义一个引用类型老师Teacher(name姓名,age年龄,salary薪水)的数组,按老师的年龄排序(降序),如果年龄相同,则按薪水排序(升序)(两种比较器各实现一次)(10)
test类
public class test {
public static void main(String[] args) {
Teacher[] arr = { new Teacher("赵国栋", 54, 9000), new Teacher("马华", 76, 8900), new Teacher("三儿子", 34, 7800),
new Teacher("你带事", 34, 8800), new Teacher("刘哥", 23, 1200) };
// 排序前
System.out.println("排序前");
for (Teacher teacher : arr) {
System.out.println(teacher);
}
ArrayUtils.sort(arr);
System.out.println("排序后");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
ArrayUtil类
package test_1106.copy;
/**
*
* @author Condi
* @Date 2020年11月6日
*/
public class ArrayUtils {
private ArrayUtils() {
}
public static void sort(Object [] arr) {
boolean flag = true;
//2、处理数据 排序
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
Comparable com1 = (Comparable)arr[j];
Comparable com2 = (Comparable)arr[j+1];
if(com1.compareTo(com2) > 0) {
Object temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = false;
}
}
if(flag) {
break;
}
}
}
}
Comparable 接口
package test_1106.copy;
/**
*
* @author Condi
* @Date 2020年11月6日
*/
public interface Comparable {
public int compareTo(Object obj);
}
Teacher 类
package test_1106.copy;
/**
*
- @author Condi
- @Date 2020年11月6日
*/
public class Teacher implements Comparable{
/** 1、定义一个引用类型老师Teacher(name姓名,age年龄,salary薪水)的数组,
* 按老师的年龄排序(降序),如果年龄相同,则按薪水排序(升序)(两种比较器各实现一次)(10)
* @param args
*/
String name;
int age;
double salary ;
/**
*
*/
public Teacher() {
super();
}
/**
* @param name
* @param age
* @param salary
*/
public Teacher(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the salary
*/
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Teacher [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
/**
* @param salary the salary to set
*/
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public int compareTo(Object obj) {
Teacher other = (Teacher) obj;
if(this.getAge()==other.getAge()) {
if(this.getSalary()>this.getSalary()) {
return -1;
}
else {
return 1;
}
}else {
return this.getAge()-other.getAge();
}
}
}