I tried to detect if an ArrayList contains the same coppies of an object with no success. Here is my code;
public class Foo{
int id;
int name;
@Override
public boolean equals(Object o){
Foo f = (Foo)o;
return f.id==this.id;
}
}
//in another class
ArrayList<Foo> foos;
...
boolean ifFoosListContainsMultipleFoo(Foo f){
return foos.indexOf(f)!=foos.lastIndexOf(f);
}
//but this method always returns `false` even the `foos` list
//contains multiple object with the same `id`;
So, what am I doing wrong and is there a more optimal way of doing this?
Thanks in advance.
EDIT: I saw that I need to override hash method of the Foo class, then why equals function is not enough;
EDIT 2: Sorry for wasting your time but it was my mistake. There is no problem with my code, I used ifFoosListContainsMultipleFoo as !ifFoosListContainsMultipleFoo so this was result of false response.
Apologize me.
Your code should work as it is, except in the case where f is not present in the list at all..
So you can do something like,
boolean ifFoosListContainsMultipleFoo(Foo f){
return (foos.indexOf(f) != -1) && (foos.indexOf(f)!=foos.lastIndexOf(f));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With