2015-04-01 27 views
1

方法的阿比說contains()方法在列表預期

「如果此列表包含指定的元素,則返回true無法正常工作。更正式,返回true,當且僅當此列表包含至少一個元素e(2 O == NULLé== NULL:o.equals(e)項) 「

我推翻了equals()方法在我的課,但仍然返回我的不實當我檢查

我的代碼

class Animal implements Comparable<Animal>{ 
    int legs; 
    Animal(int legs){this.legs=legs;} 
    public int compareTo(Animal otherAnimal){ 
     return this.legs-otherAnimal.legs; 
    } 
    public String toString(){return this.getClass().getName();} 

    public boolean equals(Animal otherAnimal){ 
     return (this.legs==otherAnimal.legs) && 
       (this.getClass().getName().equals(otherAnimal.getClass().getName())); 
    } 

    public int hashCode(){ 
     byte[] byteVal = this.getClass().getName().getBytes(); 
     int sum=0; 
     for(int i=0, n=byteVal.length; i<n ; i++) 
      sum+=byteVal[i]; 
     sum+=this.legs; 
     return sum; 
    } 

} 
class Spider extends Animal{ 
    Spider(int legs){super(legs);} 
} 
class Dog extends Animal{ 
    Dog(int legs){super(legs);} 
} 
class Man extends Animal{ 
    Man(int legs){super(legs);} 
} 

赦免類背後的壞概念,但我只是測試瞭解我的概念。

現在當我試試這個,它打印false即使是平等重寫

List<Animal> li=new ArrayList<Animal>(); 
Animal a1=new Dog(4); 
li.add(a1); 
li.add(new Man(2)); 
li.add(new Spider(6)); 

List<Animal> li2=new ArrayList<Animal>(); 
Collections.addAll(li2,new Dog(4),new Man(2),new Spider(6)); 
System.out.println(li2.size()); 
System.out.println(li.contains(li2.get(0))); //should return true but returns false 
+4

蜘蛛有8條腿:) – Steve 2015-04-01 12:12:39

回答

4

你超載equals,而不是覆蓋它。要覆蓋Objectequals方法,您必須使用相同的簽名,這意味着參數必須是Object類型。

更改爲:

@Override 
public boolean equals(Object other){ 
    if (!(other instanceof Animal)) 
     return false; 
    Animal otherAnimal = (Animal) other; 
    return (this.legs==otherAnimal.legs) && 
      (this.getClass().getName().equals(otherAnimal.getClass().getName())); 
} 
+2

請注意,當您打算覆蓋函數時使用'@ Override'註釋將有助於防止這樣的錯誤。 – Thirler 2015-04-01 12:45:06

1

作爲JLS-8.4.8.1 specify

實例方法M1,在C類聲明,覆蓋另一個實例 方法平方米,在A類聲明,如果滿足以下所有的都真:

C is a subclass of A. 

The signature of m1 is a subsignature of the signature of m2. 

Either: 

m2 is public, protected, or declared with default access in the same package as C, or 

m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2. 

簽名必須相同才能覆蓋哪些在你的情況下被忽略!