java - 调用不同类的函数

标签 java list

我正在编写一个程序,我应该在调用它之前检查并查看某个对象是否在列表中。我设置了 contains() 方法,该方法应该使用我在 上实现的 Comparable 接口(interface)的 equals() 方法Golfer 类,但它似乎没有调用它(我放入打印语句来检查)。我似乎无法弄清楚代码有什么问题,我用来浏览列表的 ArrayUnsortedList 类甚至使用了我定义的正确的 toString() 方法在我的 Golfer 类中,但由于某种原因,它不会使用我实现的 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 函数调用 Listfind() 部分中的 equals 函数> 但我不太清楚为什么,就像我打印出来时所说的那样,它可以与我完美实现的 toString() 方法一起使用。

我几乎肯定问题与 ArraySortedList 中的 find() 函数没有调用我的 equals() 方法有关。我尝试使用一些依赖于 find() 方法的其他函数并得到了相同的结果。

最佳答案

您的equals方法应该采用对象参数,而不是高尔夫球手。 equals(Golfer) 方法重载了 Comparableequals(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/

相关文章:

java - 指定三星我的文件开始位置

java - 泛型将子类添加到数组

java - SWING 的轮类日历

Python:对列表列表进行排序

list - 更新数据验证列表范围

java - 将 JDBC ResultSet 迁移到 JPA List 对象

Java程序在单行中交换两个变量?

python - 按值对字典排序并返回字典,而不是元组列表

python - 从一组整数中随机采样

css - 将级联列表样式化到表中