0

Let's say I initialize an ArrayList using the following code:

 ArrayList fib = new ArrayList();

    fib.add(18);
    fib.add(23);
    fib.add(37);
    fib.add(45);
    fib.add(50);
    fib.add(67);
    fib.add(38);
    fib.add(88);
    fib.add(91);
    fib.add(10);

What if I want to reference a specific index of the array. I don't want what's in the index. I want the index itself. I know this seems redundant, but it spills into another code.

To reference what's IN the index, I would do this:

 fib.temp(4);

and it would yield

50

What if I want what index it is?

5
  • Given the fact that List is 0 indexed, wouldn't it return 50...? Commented Jan 30, 2014 at 5:42
  • 1
    Your question is very inconsistent, using temp and fib almost interchangably - and then referring to your list as an array, which it certainly isn't... A lot of the discipline of software engineering is paying attention to the details. Please take more care in your next question. Commented Jan 30, 2014 at 5:44
  • You are mixing up ArrayList with Array, what you want, Array can do that for you... Commented Jan 30, 2014 at 6:23
  • fib.get(3), where 4 is a 0 based index, returns 45 Commented Jan 30, 2014 at 6:28
  • Apologies, everyone. This question was posted in a rush. I'm usually very considerate of my writing. Thank you for your edits, answers, and comments. Commented Jan 30, 2014 at 6:45

1 Answer 1

3

I suspect you're looking for List.indexOf:

int index = fib.indexOf(45); // index is now 3

indexOf returns -1 if the value isn't found in the list.

Note that temp isn't a member of ArrayList, and if you use fib.get(4) it will return 50, not 45 - because the index is 0-based, not 1-based.

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

5 Comments

So it would be temp.indexOf(4)? And that would return...4?
@priya No, it would return -1 based on the example. temp.indexOf(50) would return 4...
@priya: No, it would be temp.indexOf(45). Or maybe fib.indexOf(45) - the naming in your question is inconsistent. Either way, that would return 3.
@JonSkeet That makes sense. I feel foolish for forgetting counting starts at 0. Thanks.
And yes - I mixed up the ArrayList names. It should be: ArrayList fib = new ArrayList();

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.