请按照下列要求编写程序。 (1)编写一个Teacher类,包含name和age属性,提供有参构造方法。 (2)在Teacher类中,重写tostring()方法,输出age和name的值。 按年龄升序排列,年龄相同则按名宇升序排列。 "Lucy", "23" "Lily", "25" "Mary". "24" "Lisa". "24" 输出结果 [Person [name=Lucy, age=23], Person [name-Lisa, age=24], Person [name=Mary, age=24], Person [name=Lily, age=25]]
时间: 2023-07-06 08:24:39 浏览: 72
以下是Java代码实现:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Teacher {
private String name;
private int age;
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public static void main(String[] args) {
ArrayList<Teacher> teachers = new ArrayList<>();
teachers.add(new Teacher("Lucy", 23));
teachers.add(new Teacher("Lily", 25));
teachers.add(new Teacher("Mary", 24));
teachers.add(new Teacher("Lisa", 24));
Collections.sort(teachers, new Comparator<Teacher>() {
@Override
public int compare(Teacher o1, Teacher o2) {
if (o1.age == o2.age) {
return o1.name.compareTo(o2.name);
}
return o1.age - o2.age;
}
});
System.out.println(teachers);
}
}
```
输出结果为:
```
[Person [name=Lucy, age=23], Person [name=Lisa, age=24], Person [name=Mary, age=24], Person [name=Lily, age=25]]
```
阅读全文