0

I have an ArrayList of ArrayLists of T, and I am trying to find the index of the ArrayList that contains a certain object

private int indexOfItem(T item)
{
    int index = 10000;

    for(int i = 0; i < bigList.size(); i++)
    {
        if(bigList.get(i).contains(item))
        {
            index = i;
        }

    }
    return index;
}

this works but is there a better way to do this using the indexOf() method that arrayLists have?

2
  • you can do return i; in your if clause Commented Apr 4, 2016 at 18:50
  • Why do you return 10000 by default? Why not some impossible value like -1 instead? indexOf() would return the index of a list that is equal to item, and that is obviously not possible. because a list of items is never equal to an item. Commented Apr 4, 2016 at 18:52

1 Answer 1

1

That is exactly what indexOf does with one exception: As soon as you find the item, you can stop looking:

private int indexOfItem(T item) {
  for(int i = 0; i < bigList.size(); i++) {
    if(bigList.get(i).contains(item)) {
      return i;
    }
  }
  return -1;
}
Sign up to request clarification or add additional context in comments.

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.