1

I have an exam and this was in the mock and im not quite sure how to go about it, this isn't homework its simply trying to understand how to do it. Thanks.

public class Book{
private final String title;
private final String author;
private final int edition;

private Book(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 String getEdition()
{
return edition;
}

}

I need to provide implementations of equals, hashCode and compareTo methods for the above code.

I'm not to sure how to go about it, would it be somthing similar to this for the compareTo method?

title.compareTo(title);
author.compareTo(author);
edition.compareTo(edition);

Thanks, any help would be greatly appreciated.

  • 1
    See [this question](http://stackoverflow.com/q/27581/69875) for a nice summary of `equals()` and `hashCode()`. – Jonathan May 23 '13 at 13:46

3 Answers3

0

your compareTo should be this:

title.compareToIgnoreCase(otherTitle);  
...  

equals:

if(null == title || null == author || null == editor)  
{  
      return false;
}  
if(!title.equals(otherTitle)  
{
    return false;  
}    
if(!author.equals(otherAuthor)  
{  
     return false;  
}  
if(!editor.equals(otherEditor)  
{  
        return false;  
}    
return true;
Woot4Moo
  • 22,887
  • 13
  • 86
  • 143
0

Take look at this.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/package-summary.html

You can use the builders in this package to create default implementations.

Sumit
  • 1,641
  • 1
  • 13
  • 17
0

IDEs like Eclipse can generate hashCode and equals methods for you (Source -> generate hashCode() and equals()). You can even specify which fields of the object need to match for it to be considered "equal".

For instance here is what Eclipse generates for your class:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((author == null) ? 0 : author.hashCode());
    result = prime * result + edition;
    result = prime * result + ((title == null) ? 0 : title.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Book other = (Book) obj;
    if (author == null) {
        if (other.author != null)
            return false;
    } else if (!author.equals(other.author))
        return false;
    if (edition != other.edition)
        return false;
    if (title == null) {
        if (other.title != null)
            return false;
    } else if (!title.equals(other.title))
        return false;
    return true;
}
Greg Leaver
  • 801
  • 6
  • 10