I am currently revising for an upcoming exam and I'm confident in saying that I will most likely get a question that will require me to implement equals method, compareTo method and hashCode method. It is open book therefore I want to try and take full advantage of this because I think it could be especially useful for this area. For example, I managed to implement the compareTo method by following someone elses code and then adjusting it, I want this advantage in the exam as others will = )
Anyway, I have a sample exam question given to us and it asks us exactly this. I'm attempting to implement the equals method whilst using other peoples code as examples because I will be taking these in with me as a template in case they do show up, since it is allowed. However, the equals method doesn't seem as easy to implement through a template as the compareTo. I have attempted it but it doesn't seem to be going great =D I was hoping you guys could help me out on where I'm going wrong, I think although I'm not certain it could be possibly my If statement. Finally, if you have any tips for any of the methods above in an open book exam then I'll extremely appreciate it! As I'm really worried/uncertain whether or not I'll pass = )
Anyway I have been given the following code :
public class Books {
private final String title;
private final String author;
private final int edition;
public Books(String title, String author, int edition)
{
this.title = title;
this.author = author;
this.edition = edition;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
public int getEdition(){
return edition;
}
With this code I'm to implement the equals method and here's the attempt I made at doing it whilst following someone elses.
public boolean equals(Object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if(getClass() != obj.getClass())
return false;
Books other = (Books) obj;
if (getTitle() == null){
if (other.getTitle() != null)
return false;
}
else if
(!getTitle().equals(other.getTitle()))
return false;
return true;
else if (getAuthor() == null){
if (other.getAuthor() != null)
return false;
}
else if
(!getAuthor().equals(other.getAuthor()))
return false;
return true;
if (getEdition() != other.getEdition())
return false;
}
I know I've pretty much screwed how the if statement flows, I struggled to follow it through nicely as it's grown =/