【发布时间】:2016-12-11 12:23:15
【问题描述】:
我需要按照下面的方法实现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);}}}
【问题讨论】:
-
您想使用 Map
代替。此外,还有可怕的 equals方法。
标签: java object equals indexof