java - contains() method in List not working as expected -
the api of contains() method says
"returns true if list contains specified element. more formally, returns true if , if list contains @ least 1 element e such (o==null ? e==null : o.equals(e)). "
i overrode equals() method in class contains() still returns me false when check
my code
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);} }   pardon bad concept behind classes testing understanding of concepts.
now when try this, prints false though equals overriden
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 returns false      
you overloaded equals instead of overriding it. override object's equals method, must use same signature, means argument must of object type.
change to:
@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())); }      
Comments
Post a Comment