{JAVA}为我的查找方法实现equals(objecto)方法
我需要根据以下方法实现equals方法{JAVA}为我的查找方法实现equals(objecto)方法,java,object,equals,indexof,Java,Object,Equals,Indexof,我需要根据以下方法实现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){retur
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.*;
公共类数据库{
//宣布一份赞助人名单
ArrayList赞助人;
//建造师
公共数据库()
{
用户=新的ArrayList();
}
//[5点]添加用户对象的方法。它
//如果用户已经存在,则返回false,
//否则返回true。您应该使用
//查找方法如下。
公共布尔加法(用户p){
if(查找(p.id)==null){
用户。添加(p);
返回true;
}
其他的
返回false;
}
//[5点]使用帮助器查找用户的方法
//id。如果找到,则返回,否则返回null。
公共用户查找(int id){
int val=用户索引of(id);
如果(val!=-1){
返回用户。获取(val);
}
其他的
返回null;}}
import java.util.*;
公共级赞助人{
//数据成员:id、名称、已签出图书的列表
int-id;
字符串名;
ArrayList Books CheckedOut;
//[3分]建造师
公共用户(int-id,字符串名称)
{this.id=id;
this.name=名称;
booksCheckedOut=newarraylist();
}
//返回id的方法
公共int getID(){
返回id;
}
//[5点]需要实施这一点,以实现
//ArrayList的indexOf等方法可以正常工作
公共布尔等于(对象o){
如果(!(用户实例)){
返回false;
}
否则{
返回true;
}
}
//[2点]通过添加图书来签出图书的方法
//到上面的ArrayList
公共作废addBook(字符串书名,双书价){
图书b=新书(书名、书价);
booksCheckedOut。添加(b);
}
//[5点]列出ArrayList中的所有书籍
公开声明(){
对于(图书价值:booksCheckedOut){
System.out.println(val);}
如果希望数组列表的indexOf
返回除-1以外的任何内容,则必须向其传递用户的实例
传递一个int
,就像你在这里做的那样
int val = patrons.indexOf(id);
将始终返回-1
如果您希望能够通过用户的标识符查找用户,请使用哈希映射
,而不是列表
或者,您可以将用户查找(int-id)
更改为用户查找(p)
,并将p
传递给它,而不是add
方法中的p.id
另外,我假设您在Patron
类中实现的equals
是不完整的,因为当您将Patron
实例传递给它时,它总是返回true
。您想改用Map吗。另外,可怕的等于那里的方法。实际上,我不应该更改方法参数,因为它们是给我的(我是一名学生)。因此,我只能为给定的方法编写代码。@AbdulBasitKhan在您发布的所有方法中,哪种方法是您应该更改的方法?
int val = patrons.indexOf(id);