0

Imagine we know the size of the list and want to go through every fifth element in it only. I think if I do that with ArrayList, like below:

List<Item> l = new ArrayList<Item>();
for (int i = 0; i < l.size(); ) {
    Item item = l.get(i);
    i += 5;
}

it will indirectly iterate through every element of the list up to i each time I call l.get(i) which is stupid. Is there any way to access only every fifth element? Maybe LinkedList? Could you please give me an example on how to use the ListIterator for that purpose?

2
  • Side comment: for (int i = 0; i < l.size(); i += 5) { would be more readable. Commented Jul 24, 2012 at 10:43
  • You are right, I just wanted to everyone notice that, otherwise they could read it as usual i++. Commented Jul 24, 2012 at 10:45

2 Answers 2

3

it will indirectly iterate through every element of the list up to i each time I call l.get(i)

No it won't. get(i) in ArrayList is an O(1) operation and will fetch the item directly from the backing array - no iteration involved. See the ArrayList's javadoc:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.


On the contrary, if you use a LinkedList, it will iterate through every element and it will be less efficient, as explained in the LinkedList javadoc:

Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

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

Comments

1
it will indirectly iterate through every element of the list up to i each time I call l.get(i)

Well, as we know ArrayList is backed by an array in its implementation , so it behaves in the same as array does. So if whenever, we do get(i) ..it directly goes to that index and fetches data.

Maybe LinkedList? Could you please give me an example on how to use the ListIterator for that purpose?

If you ever gone through data structures in computer science, we know that LinkedList are implemented through pointers. means every elements points to next element and so forth so on. So in this case you can't jump through elements to get to the fifth. You will have to go to first which guides you to the second which guides you to the third and so on.

now its up to to decide which data structures to use.

3 Comments

I miss here C++ pointer arithmetics, where I could jump as many times I wanted.
Same is for ArrayList...well C++ pointers they awesome. but not good for security point of view
@SophieSperner get(i) does exactly that, a pointer jump, except that you don't have to worry about it.

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.