我需要根据以下方法实现equals方法。
public class Database{
.........
//A helper method to look for a patron using
//id. If found, it returns it, otherwise, it returns null.
public Patron lookUp(int id) {
int val = patrons.indexOf(id);
if(val!=-1){return patrons.get(val);}
else
return null;}}
equals方法是patron类,我为它编写了以下代码。
public class Patron{
.........
//Need to implement this in order to have a
//method such as indexOf of ArrayList work properly
public boolean equals(Object o) {
if(!(o instanceof Patron)){
return false;}
else{
return true;}}
所以基本上我需要使用indexOf方法检查是否存在具有提供的id号的顾客。为此,我们在Patron类中创建了equals方法。但它不起作用,总是返回-1。
以下是两个班级。
import java.util.*;
public class Database{
// Declare an ArrayList of patrons
ArrayList<Patron> patrons;
// Constructor
public Database()
{
patrons = new ArrayList<Patron>();
}
// [5 points] A method that adds a patron object. It
//returns false if the patron already exists,
//otherwise it returns true. You should use the
//lookUp method below.
public boolean add( Patron p ){
if(lookUp(p.id)==null){
patrons.add(p);
return true;
}
else
return false;
}
// [5 points] A helper method to look for a patron using
//id. If found, it returns it, otherwise, it returns null.
public Patron lookUp(int id) {
int val = patrons.indexOf(id);
if(val!=-1){
return patrons.get(val);
}
else
return null;}}
import java.util.*;
public class Patron{
//Data members: id, name, a list of checked out books
int id;
String name;
ArrayList<Book> booksCheckedOut;
// [3 points] Constructor
public Patron(int id, String name)
{ this.id = id;
this.name = name;
booksCheckedOut = new ArrayList<Book>();
}
//A method to return the id
public int getID() {
return id;
}
// [5 points] Need to implement this in order to have a
//method such as indexOf of ArrayList work properly
public boolean equals(Object o) {
if(!(o instanceof Patron)){
return false;
}
else{
return true;
}
}
// [2 points] A method to check out a book by adding it
//to the ArrayList above
public void addBook(String bookTitle, double bookPrice){
Book b = new Book(bookTitle,bookPrice);
booksCheckedOut.add(b);
}
// [5 points] List all books in the ArrayList
public void showStatement() {
for(Book val: booksCheckedOut){
System.out.println(val);}}}
答案 0 :(得分:0)
如果您希望ArrayList<Patron>
的{{1}}返回-1以外的任何内容,则必须向其传递Patron
的实例。
传递int
,就像你在这里一样
int val = patrons.indexOf(id);
将始终返回-1。
如果您希望能够按标识符查找Patron
,请使用HashMap<Integer,Patron>
代替List
。
或者您可以将Patron lookUp(int id)
更改为Patron lookUp(Patron p)
,然后在p
方法中将p.id
更改为add
。
PS,我假设您在equals
类中的Patron
实现不完整,因为当您向true
实例传递Patron
时,它始终返回10:00 AM, 31 January 2017
。 / p>