使用Java定义一个birthday类,包括年、月、日三个成员变量。默认创建一个“2000-01-01”的对象,否则按照提供的日期字符串创建对象。birthday类中定义一个排序成员方法,可以实现按年龄排序的操作。输入n个人的生日信息,按照年龄大小顺序输出
时间: 2024-02-05 20:13:52 浏览: 72
以下是Java定义的Birthday类实现:
```java
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Birthday implements Comparable<Birthday> {
private int year;
private int month;
private int day;
public Birthday() {
this.year = 2000;
this.month = 1;
this.day = 1;
}
public Birthday(String dateStr) {
LocalDate date = LocalDate.parse(dateStr);
this.year = date.getYear();
this.month = date.getMonthValue();
this.day = date.getDayOfMonth();
}
public void setYear(int year) {
this.year = year;
}
public void setMonth(int month) {
this.month = month;
}
public void setDay(int day) {
this.day = day;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int compareTo(Birthday o) {
LocalDate date1 = LocalDate.of(year, month, day);
LocalDate date2 = LocalDate.of(o.getYear(), o.getMonth(), o.getDay());
Period period1 = Period.between(date1, LocalDate.now());
Period period2 = Period.between(date2, LocalDate.now());
return period1.getYears() - period2.getYears();
}
public static void main(String[] args) {
List<Birthday> birthdays = new ArrayList<>();
birthdays.add(new Birthday("1995-05-13"));
birthdays.add(new Birthday("1990-08-20"));
birthdays.add(new Birthday("1988-12-01"));
birthdays.add(new Birthday("1998-02-28"));
birthdays.add(new Birthday());
Collections.sort(birthdays);
for (Birthday birthday : birthdays) {
System.out.println(birthday.getYear() + "-" + birthday.getMonth() + "-" + birthday.getDay());
}
}
}
```
在这个实现中,我们使用了Java 8中的LocalDate类来处理日期,并使用Period类计算年龄。compareTo方法通过比较两个生日日期的年龄大小来实现排序。在main方法中,我们创建了一个包含多个生日对象的List,然后使用Collections.sort方法按照年龄从小到大排序,并输出结果。
阅读全文