1

我有一个考试,这是在模拟中,我不太确定如何去做,这不是家庭作业,它只是试图了解如何去做。谢谢。

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;
}

}

我需要为上述代码提供 equals、hashCode 和 compareTo 方法的实现。

我不知道该怎么做,compareTo 方法是否与此类似?

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

谢谢,任何帮助将不胜感激。

4

3 回答 3

0

看看这个。

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

您可以使用此包中的构建器来创建默认实现。

于 2013-05-23T16:39:04.407 回答
0

你的 compareTo 应该是这样的:

title.compareToIgnoreCase(otherTitle);  
...  

等于:

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;
于 2013-05-23T13:46:58.060 回答
0

像 Eclipse 这样的 IDE 可以为您生成hashCodeequals方法(Source -> generate hashCode() 和 equals())。您甚至可以指定对象的哪些字段需要匹配才能被视为“相等”。

例如,这是 Eclipse 为您的类生成的内容:

@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;
}
于 2013-05-23T16:50:40.790 回答