class Date {
private int day;
private int month;
private int year;
public Date() {
}
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return this.day;
}
public int getMonth() {
return this.month;
}
public int getYear() {
return this.year;
}
public void setDay(int day) {
day = enteredDay;
}
public void setMonth(int month) {
month = enteredMonth;
}
public void setYear(int year) {
year = enteredYear;
}
public String toString() {
return getDay() + "/" + getMonth() + "/" + getYear();
}
public boolean isEarlier(Date) {
if (enteredDay.getDay() < day) {
return true;
} else {
return false;
}
}
}
我无法使用最后一种方法。它必须是布尔值,如果日期早于它,则返回true。我的问题(至少据我所知)是弄清楚写'<'运算符任一侧的内容。对其余代码的任何反馈将不胜感激。
参考方案
我会逐年,按月和按天依次比较每个表项,直到找到严格的对表。
使用Comparator
尤其是Java 8的简洁语法,可以在这里节省很多样板代码:
public boolean isEarlier(Date other) {
return Comparator.comparingInt(Date::getYear)
.thenComparingInt(Date::getMoth)
.thenComparingInt(Date::getDay)
.compare(this, other) < 0;
}
编辑:
要回答评论中的问题,您当然可以手动比较每个字段:
public boolean isEarlier(Date other) {
if (getYear() < other.getYear()) {
return true;
} else if (getYear() > other.getYear()) {
return false;
}
// If we reached here, both dates' years are equal
if (getMonth() < other.getMonth()) {
return true;
} else if (getMonth() > other.getMonth()) {
return false;
}
// If we reached here, both dates' years and months are equal
return getDay() < other.getDay();
}
当然,这可以压缩为单个布尔值语句,尽管在旁观者看来,它是更优雅还是更不优雅(严格不需要括号,但是恕我直言,它们使代码更清晰):
public boolean isEarlier(Date other) {
return (getYear() < other.getYear()) ||
(getYear() == other.getYear() &&
getMonth() < other.getMonth()) ||
(getYear() == other.getYear() &&
getMonth() == other.getMonth() &&
getDay() < other.getDay());
}
java:继承 - java有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…
Java:BigInteger,如何通过OutputStream编写它 - java我想将BigInteger写入文件。做这个的最好方式是什么。当然,我想从输入流中读取(使用程序,而不是人工)。我必须使用ObjectOutputStream还是有更好的方法?目的是使用尽可能少的字节。谢谢马丁 参考方案 Java序列化(ObjectOutputStream / ObjectInputStream)是将对象序列化为八位字节序列的一种通用方法。但…
Java-如何将此字符串转换为日期? - java我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…
Java:从类中查找项目名称 - java仅通过类的实例,如何使用Java反射或类似方法查找项目名称?如果不是,项目名称(我真正想要的是)可以找到程序包名称吗? 参考方案 项目只是IDE使用的简单组织工具,因此项目名称不是类或JVM中包含的信息。要获取软件包,请使用Class#getPackage()。然后,可以调用Package#getName()将包作为您在代码的包声明中看到的String来获取…
Java:“自动装配”继承与依赖注入 - javaImprove this question 我通常以常见的简单形式使用Spring框架: 控制器服务存储库通常,我会在CommonService类中放一个通用服务,并使所有其他服务扩展到类中。一个开发人员告诉我,最好在每个服务中插入CommonClass而不是使用继承。我的问题是,有一个方法比另一个更好吗? JVM或性能是否会受到另一个影响?更新资料Comm…