• Post Reply Bookmark Topic Watch Topic
  • New Topic

why was .length used in this loop?  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

was watching a video on polymorphism

he had

Insect allInsects [] = new Insect[3];

allInsects [0] = new Roach();
allInsects [1] = new spider();
allInsects [2] = new beatle();

    for (int i=0; 1 < allInsects.length; i++) {
    allInsects [i].eat();

now i did get what the video was explaining,but looking at the code what does .length do in the for loop?
i is 0, so i up to allInsects.length ...then it iterates

why would you need character length to manage a for loop?






 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry 1 should be i in < allInsects.length; i++)

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The length field is available with all array objects, and it is set to the size of the array.

Henry
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh...is allInsects.length just telling the loop to go over each item (the length) of the array?
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
allInsects is an array. length is the length of the array, which in this case is 3.
 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just saw your answer now thanks henry
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer to the original question is that form of a for loop is reliable; it is certain to iterate the array visiting every element and can never run out of the bounds of the array. You can read a bit more about members of arrays in the Java® Language Specification. Beware: that might be difficult to read.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!