Jorge Jorge - 3 months ago 10x
Android Question

Array Index of object - java

I have an arraylist of mobile objects.

  • Mobile:

    • MobileID

    • MobileName

My arraylist contains N number of Mobile objects.

I have only the MobileID and I need to find the index of that object.

I was trying arraylist.indexOf but i don't know how compare the MobileID of the object inside the array with my variable(mobID)


In your Mobile class, override the boolean equals(Object o) method and return true when two objects' ids are equal.

class Mobile {
    boolean equals(Object obj) {
        if (obj instanceof Mobile) {
            Mobile otherMobile = (Mobile)obj;
            return otherMobile.getMobileID().equals(this.getMobileID());
        return false;


If you are sure in your future code, the equality of the Mobile will remain the same, which is, solely compared by id, then this way is easier. But, if that's not the case, then, loop through all the elements, and compare the id, returns the match element's index is a better way.