我正在编写一个程序,我应该在调用它之前检查并查看某个对象是否在列表中。我设置了 contains()
方法,该方法应该使用我在 上实现的
类,但它似乎没有调用它(我放入打印语句来检查)。我似乎无法弄清楚代码有什么问题,我用来浏览列表的 ArrayUnsortedList 类甚至使用了我定义的正确的 toString() 方法在我的 Comparable
接口(interface)的 equals()
方法GolferGolfer
类中,但由于某种原因,它不会使用我实现的 equals()
方法。
//From "GolfApp.java"
public class GolfApp{
ListInterface <Golfer>golfers = new ArraySortedList<Golfer> (20);
Golfer golfer;
//..*snip*..
if(this.golfers.contains(new Golfer(name,score)))
System.out.println("The list already contains this golfer");
else{
this.golfers.add(this.golfer = new Golfer(name,score));
System.out.println("This golfer is already on the list");
}
//From "ArrayUnsortedList.java"
protected void find(T target){
location = 0;
found = false;
while (location < numElements){
if (list[location].equals(target)) //Where I think the problem is
{
found = true;
return;
}
else
location++;
}
}
public boolean contains(T element){
find(element);
return found;
}
//From "Golfer.java"
public class Golfer implements Comparable<Golfer>{
//..irrelavant code sniped..//
public boolean equals(Golfer golfer)
{
String thisString = score + ":" + name;
String otherString = golfer.getScore() + ":" + golfer.getName() ;
System.out.println("Golfer.equals() has bee called");
return thisString.equalsIgnoreCase(otherString);
}
public String toString()
{
return (score + ":" + name);
}
我的主要问题似乎是让 ArrayUnsortedList
的 find 函数调用 List
的 find()
部分中的 equals 函数> 但我不太清楚为什么,就像我打印出来时所说的那样,它可以与我完美实现的 toString()
方法一起使用。
我几乎肯定问题与 ArraySortedList
中的 find()
函数没有调用我的 equals()
方法有关。我尝试使用一些依赖于 find()
方法的其他函数并得到了相同的结果。
最佳答案
您的equals
方法应该采用对象参数,而不是高尔夫球手。 equals(Golfer)
方法重载了 Comparable
的 equals(Object)
方法,但未实现它。它只是一个其他代码不知道的重载方法,因此不会被调用。
public boolean equals(Object obj)
{
if(!(obj instanceof Golfer)) return false;
Golfer golfer = (Golfer)obj;
String thisString = score + ":" + name;
String otherString = golfer.getScore() + ":" + golfer.getName() ;
System.out.println("Golfer.equals() has bee called");
return thisString.equalsIgnoreCase(otherString);
}
关于java - 调用不同类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12585540/