Iterating through a variable length array

前端 未结 4 1431
囚心锁ツ
囚心锁ツ 2020-12-03 13:54

How do I iterate over a Java array of variable length.

I guess I would setup a while loop, but how would I detect that I have reached the end of the array.

4条回答
  •  隐瞒了意图╮
    2020-12-03 14:28

    You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.

    Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:

    Collection things = ...;
    for (Thing t : things) {
      System.out.println(t);
    }
    

    EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.

提交回复
热议问题