Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if ArrayList contains multiple instance of the same object

Tags:

java

arraylist

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.

like image 403
Ismail Sahin Avatar asked Oct 30 '25 15:10

Ismail Sahin


1 Answers

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));
}
like image 145
Codebender Avatar answered Nov 01 '25 03:11

Codebender