メソッドのAPIはcontains()
言う
"このリストに指定された要素が含まれている場合に true を返します。より正式には、(o==null ? e==null : o.equals(e)) のような要素 e がこのリストに少なくとも 1 つ含まれている場合にのみ、true を返します。"
equals()
クラスのメソッドをオーバーライドしましたが、contains()
チェックすると false が返されます
私のコード
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
、 equals がオーバーライドされていても印刷されます
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