Reputation: 2710
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.
Upvotes: 4
Views: 2096
Reputation: 31339
You can use a HashSet<Foo>
to do this. You should override hashCode
as well because HashSet
uses hashes internally.
Set<Foo> set = new HashSet<Foo>(foos);
// check for duplicates
set.size() == foos.size();
You can also use the set manually which should let you retain the duplicates and can let you end the check sooner (instead of adding everything):
Set<Foo> set = new HashSet<Foo>();
// check for duplicates
for (Foo foo : foos){
if (!set.contains(foo)){
set.add(foo);
} else {
// do something with foo, which is a duplicate.
// possibly end check for duplicates or store in a list
}
}
Upvotes: 2
Reputation: 14471
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));
}
Upvotes: 4