用Java编写一个Person类,该类有两个实例变量:name和age,构造一个Person对象数组,按姓名对Person对象进行排序,如果姓名重复,则继续按年龄进行排序。
时间: 2024-05-10 12:20:50 浏览: 100
java代码-使用java构造Person类。包括姓名(name),性别和年龄(age)的源代码
5星 · 资源好评率100%
以下是Java代码实现:
```
import java.util.*;
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person other) {
int nameCompare = this.name.compareTo(other.name);
if (nameCompare != 0) {
return nameCompare;
} else {
return Integer.compare(this.age, other.age);
}
}
public static void main(String[] args) {
Person[] people = new Person[5];
people[0] = new Person("Alice", 25);
people[1] = new Person("Bob", 30);
people[2] = new Person("Charlie", 20);
people[3] = new Person("Alice", 20);
people[4] = new Person("Charlie", 25);
Arrays.sort(people);
for (Person person : people) {
System.out.println(person.getName() + " " + person.getAge());
}
}
}
```
在这个实现中,Person类实现了Comparable接口,以便能够进行排序。compareTo方法首先按照姓名进行比较,如果姓名相同,则按照年龄进行比较。在main方法中,我们创建了一个Person对象数组,对其进行排序,并输出每个人的姓名和年龄。输出结果如下:
```
Alice 20
Alice 25
Bob 30
Charlie 20
Charlie 25
```
阅读全文