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

あなたの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メソッドを生成できます (ソース -> 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 に答える
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 に答える