0

I have encountered the following question: The length operator can be used to control a for-loop that iterates through each element of an array, as in

for (int j=0; j<list.length; j++)

However, this is not necessarily safe. Why not?

Is there any merit to this question or is it just crazy?

2
  • 3
    My guess would be that the questioner aims at problems that can happen when the list is altered while you iterate. For example if an element is deleted. Not sure though. Commented Nov 16, 2014 at 0:58
  • I'm sorry I might be unclear, its an array not a list, the identifier is called 'list' but its talking about hard arrays that cannot delete elements Commented Nov 16, 2014 at 1:05

2 Answers 2

1

It's safe if list has been checked for null. For example,

int len = (list != null) ? list.length : 0;
for (int j = 0; j < len; j++)

Then len will be 0 if list is null. In your posted version, when list = null; you could get a NullPointerException.

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

Comments

0

It depends.

If you're just doing your standard traversal through the list, you may as well just use a foreach. If you need the index for some operation though, it's usually okay to do what you said.

One thing to be careful of though is will the size of the list change? For example, if you remove an element somewhere in the iteration, there will be an element at the end that you won't iterate over.

Another thing to be VERY careful of is if this is not a List but rather a Collection. Unlike lists, collections make no promises on the order of elements. If you add or remove an element in the collection, all the indices could change.

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.