0

I've a class A which is as follows:

A{
     String name;
     ArrayList<Bike> firstArray;
     ArrayList<Cycle> secondArray;
     // it's constructors and related methods are down lines.
 }

and I have two instances of it named a_Obj and b_obj. I compare only the variable ,name inside object a_Obj with b_Obj using indexOf.

My question is how to call indexOf in this case and in other words how to tell the compiler that I just want to compare name of two objects regardless of ArrayLists declared inside the class A.

0

2 Answers 2

1

you can override equals() in your class

Sign up to request clarification or add additional context in comments.

Comments

0

Given below is how indexOf has been implemented by default:

public int indexOf(Object o) {
    ListIterator<E> it = listIterator();
    if (o==null) {
        while (it.hasNext())
            if (it.next()==null)
                return it.previousIndex();
    } else {
        while (it.hasNext())
            if (o.equals(it.next()))
                return it.previousIndex();
    }
    return -1;
}

By overriding the equals method in A to consider just the equality of name, you can make it happen.

Given below is the definition generated by Eclipse IDE:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    A other = (A) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}

A shorter version for the same can be as follows:

@Override
public boolean equals(Object obj) {
    if (obj == null)
        return false;
    A other = (A) obj;
    return Objects.equals(name, other.name);
}

2 Comments

return name.equals(other.name);
@WJS - I do not approve your suggested solution as it will throw NullPointerException when name is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.