2012-09-23 39 views
0

我正在編寫程序,我應該在調用它之前檢查並查看某個對象是否在列表中。我設置了方法,該方法應該使用我在Golfer類上實現的Comparable接口的equals()方法,但它似乎沒有調用它(我把打印語句放在檢查中)。我似乎無法弄清楚代碼有什麼問題,我使用的ArrayUnsortedList類通過列表,甚至使用我在Golfer類中定義的正確的toString()方法,但由於某種原因,它不會使用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的查找功能打電話給我平等的功能在Listfind()一部分,但我不知道是什麼原因,就像我說的,當我有它打印出來它適用於我完美實施的toString()方法。

我幾乎積極的問題與中的find()函數沒有調用我的equals()方法有關。我嘗試使用一些依賴於find()方法的其他函數,並得到了相同的結果。

+0

您的高爾夫球員的球員是否真的實施了比較?例如:「public class Golfer implements Comparable」 – ssgriffonuser

+0

是的,我應該包括像頂部的變量一樣。它也使用了泛型,因爲我還沒有完全理解它,我不確定這是否是問題所在。 – adc90

+0

阻止你通過代碼來查看發生了什麼? – James

回答

1

您的equals方法應該採取Object參數,而不是高爾夫球員。 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); 
}