Jorge Jorge - 1 year ago 68
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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download