1

I want to retrive index of specific element of my list :

    ArrayList<Field> list = new ArrayList<Field>();
    list.addAll(profile.getFieldsList());

    Object privacyName = "privacy";
    int i = list.indexOf(privacyName);
    boolean doesContain = list.contains(privacyName);

There is a field containing "privacy" in the list but i is always -1 and doesContain is always false. Why this search doesn't work ?

2
  • 1
    Your List contains element of type Field, which cannot have the value "privacy". Do you have some property of Field, for which you are having that value? Commented Aug 7, 2013 at 13:45
  • I think it is cause of Object you are using and not Filed? Commented Aug 7, 2013 at 13:45

4 Answers 4

3

Why this search doesn't work ?

Because list contains instances of the Field class and you are calling the contains method passing a String instance.

To make it work you need to pass an instance of the Field class.

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

2 Comments

So how I can do this for 'Field' type ?
The problem is he's passing an instance of String which can't possibly be a Field.
1
    public int indexOf(Object o) {
         if (o == null) {
             for (int i = 0; i < size; i++)
                 if (elementData[i]==null)
                     return i;
         } else {
             for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
   }

You need to override equals for logical equality or rely on default for reference equality.

In this case privacyName.equals(elementData[i]) is always false.

Comments

1

From the Java docs for indexOf:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

So your list does not contain the object privacyName;

Comments

1

In ArrayList Index of method will based on equals method. In field class overide equals and hasCode method of Object class. And you told that "There is a field containing "privacy" in the list" . IndexOf Array will based on equals method. As @rocketboy's ans, u need to overide equals as well as hasCode method properly. Why do I need to override the equals and hashCode methods in Java?

Comments

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.