public class TestLibraryBook {
public static void main(String[] args) {
LibraryBook book1, book2;
book2 = new LibraryBook("Ali's book", "Ali", "1st June", 250);
book1 = book2;
LibraryBook book5, book6;
LibraryBook book3, book4;
LibraryBook book7, book8, book9, book10;
book4 = new LibraryBook("David's Labs", "David", "29 of February", 1);
book3 = book4;
book6 = new LibraryBook("James adventure", "James", "May", 25);
book5 = book6;
book7 = new LibraryBook("James holiday", "Jane", "Jun", 31);
book8 = book7;
book9 = new LibraryBook("James holiday", "Jane", "April", 53);
book10 = book9;
}
}
这是我的第二堂课
public class LibraryBook {
// variables
public String title;
public String author;
public String dueDate;
public int timesLoaned;
// constructor
public LibraryBook(String title, String author, String dueDate, int timesLoaned) {
this.title = title;
this.author = author;
this.dueDate = dueDate;
this.timesLoaned = timesLoaned;
}
// constructor
public LibraryBook() {
title = "no info";
author = "no info";
dueDate = " no info ";
timesLoaned = 0;
}
public boolean equals() {
if (title.equals(title) & author.equals(author)) {
return true;
}
return false;
}
}
我有两个带有对象和引用的类,我想说一下它们的title
和author
是否相同。因此,我想在我的boolean equals
类中添加LibraryBook
方法,以便将具有相同title
和author
的书籍视为相同的书籍,而不考虑其dueDate
或timesLoaned
。我无法做到这一点,请帮助我。
答案 0 :(得分:0)
如果您不是Netbeans,则只需右键单击您的类,然后生成代码,等于和哈希代码,然后仅选择标题,Netbeans将为您自动生成该方法。方法的问题在于,您正在将对象与其自身进行比较,您需要接收另一个LibraryBook
作为参数并比较2。
public boolean equals(LibraryBook other)
{
if(this.title.equals(other.title) && this.author.equals(other.author))
{
return true;
}
return false;
}
}
答案 1 :(得分:0)
编写equals
方法如下:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LibraryBook other = (LibraryBook) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}