This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a question,
I'm making a class employer where there are 3 properties:
1) int day;
Now the problem is i want to compare the inputted dates.
My class implements Comparable, I have already written the equals()-method.
But now I am stuck on the compareTo- method...
I want it to rank the date lower if the the dates are equal or lower, and higher if there higher.
I added my code, it's written in dutch though, so I hope it doesn't make things too difficult.
the WerknemersDatum is my own class with the 3 properties and there setters and getters.
Thanks in advance,
PS as you can see I tried but misarably failed.
Kenneth Van Gysegem wrote:The thing is the compareTo gets an errormessage: "returnstatement missing", but I don't see where.
The line if(this.datumInDienst.getJaar()==o.getDatumInDienst().getJaar()) (line 78) doesn't have a corresponding else clause. So if it hits that line and the condition is false there's no return value specified.
I'm pretty sure you can simplify it a bit, though. Have a look at java.lang.Integer#compare(int,int), which already does what is needed for a single integer. Use that on the year. If it's non-zero, just return it. Otherwise continue to the month, etc. So you only need two if statements with that.
There's also a slightly cheaty version that relies on you knowing (and enforcing) an upper limit for day and month. Just compare day + 32*(month + 13*year)).
Kenneth Van Gysegem
Joined: Mar 30, 2013
In the end I didn't do it your way but you helped me a lot with the line 78 tip!
Don't know how i could've missed it.
In the end I did it this way
I will however bear your advice in mind, and study the subject a little more.