Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为类提供equals、hashCode和compareTo方法的实现_Java_Equals_Hashcode_Compareto - Fatal编程技术网

Java 为类提供equals、hashCode和compareTo方法的实现

Java 为类提供equals、hashCode和compareTo方法的实现,java,equals,hashcode,compareto,Java,Equals,Hashcode,Compareto,我有一个考试,这是在模拟,我不太确定如何去做,这不是家庭作业,它只是试图了解如何做。谢谢 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; th

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

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

谢谢,我们将非常感谢您的帮助。

您的比较应该是:

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;
看看这个


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

Eclipse等ide可以为您生成hashCode和equals方法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;
}

有关equals和hashCode的详细摘要,请参阅。非常感谢,这将是一个很大的帮助