Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Using foreach loop to add items to an array?  RSS feed

 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From what I understand, the foreach loop loops through the items in an Array using an internal counter, like so:
It reads through the Array and creates an index that refers to the current item in the Array (in this case, the int i).
It is the same as doing this:
I tried to write an application where I could add items to an Array using this new foreach loop, but it seems I was doing something wrong:
After I noticed my mistake, I came up with the following working code:However, I had to add my own custom counter to make it work.
Is it possible to add items to an Array using a foreach loop, but without using a custom counter variable?
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:After I noticed my mistake, I came up with the following working code:However, I had to add my own custom counter to make it work.
Is it possible to add items to an Array using a foreach loop, but without using a custom counter variable?


What's wrong with using the regular for loop? Or even the while loop, which is basically similar to what you are doing.

Henry
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am simply learning the Java language step by step, construct by construct and I want to master each aspect of it.

Now I am learning the foreach loop (an improvement upon the normal older loops, introduced in JDK 1.5). I want to explore all the possible ways in which it works; its internals. If I can use a foreach loop to accomplish what I want, I am one step further. I also think the foreach loop is easier to read than the old one. Furthermore, if I perfectly understand the internals of each Java language construct, it will save me debugging time in the future, in the case I encounter such a construct.

There is also the possibility that one day a supervisor asks me to use a foreach loop and not a for/while loop.
 
Carey Brown
Bartender
Posts: 2991
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:Now I am learning the foreach loop (an improvement upon the normal older loops, introduced in JDK 1.5).
An "improvement", yes. A replacement, no. There are times when the "old" for loop is the right tool for the job.
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:
Now I am learning the foreach loop (an improvement upon the normal older loops, introduced in JDK 1.5). I want to explore all the possible ways in which it works; its internals.


Why do you believe that the foreach loop is an improvement over the regular for loop? Improvement implies that one is better for all cases than the other (or at least, it should be) -- and as you clearly noticed, that is not true. A foreach loop doesn't have access to the index, and having a second parallel index is a work-around, is cumbersome to use, and definitely, not easier to read.

Henry
 
Junilu Lacar
Sheriff
Posts: 11135
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:
Now I am learning the foreach loop (an improvement upon the normal older loops, introduced in JDK 1.5). I want to explore all the possible ways in which it works; its internals. If I can use a foreach loop to accomplish what I want, I am one step further. I also think the foreach loop is easier to read than the old one. Furthermore, if I perfectly understand the internals of each Java language construct, it will save me debugging time in the future, in the case I encounter such a construct.

There is also the possibility that one day a supervisor asks me to use a foreach loop and not a for/while loop.

Your goal of learning about the internals of the for-each loop runs counter to the reason it was created at all. The whole point of the for-each loop is so that the programmer doesn't really have to care about the internal details of iteration -- the only code the programmer needs to write is the logic that deals with each element. The main thing to understand about it is that it hides the iteration details. You should also know the different situations where the for-each loop should not be used, listed in the last paragraph of this page. Your example is one such situation. If your supervisor someday tells you to use the for-each loop inappropriately, you can also point him/her to that page.
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Why do you believe that the foreach loop is an improvement over the regular for loop?

Because the book I am reading (Murach's Java SE 6) refers to the foreach loop as 'enhanced for loop':

For loops are often used to process arrays. Version 1.5 of the JDK also introduced a new type of for loop, called an enhanced for loop or a foreach loop, that lets you process each element of an array without using indexes.

Other sources refer to this name as well:
https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with
http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/enhanced-for-loops.html

The definition for 'enhance' can be found here and its synonym here.
Thus, one of the reasons I assume it is an improved version of the for loop is the wording.
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:
Thus, one of the reasons I assume it is an improved version of the for loop is the wording.


Well, now that you played with the enhanced for loop, do you still regard it as an improvement. Or is it just a different kind of loop?

Henry
 
Liutauras Vilda
Marshal
Posts: 4634
316
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:If I can use a foreach loop to accomplish what I want, I am one step further. I also think the foreach loop is easier to read than the old one.
Hi, once again what you have been told already.

Four loops: while, do-while, for, for each, has a different purpose and each of them best suit in certain situations.
Word "enhanced" you likely understood mistakenly, by direct definition. The other name is "for each" which is more accurate in my opinion.

With "for each" loop you cannot iterate array backwards, as index cannot be accessed directly. You cannot iterate till half the size of array. So, as you see there are things which you cannot accomplish with "for each" loop, but you could easily accomplish with "while" or "for" loops.

So you cannot state that "for each" is better than the others - these are just different and for different purpose.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't write long lines in your code. I broke a few long lines up for you.
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:
Because the book I am reading (Murach's Java SE 6) refers to the foreach loop as 'enhanced for loop':

For loops are often used to process arrays. Version 1.5 of the JDK also introduced a new type of for loop, called an enhanced for loop or a foreach loop, that lets you process each element of an array without using indexes.

Context is important. The name "enhanced for loop" is a little unfortunate, but see how it is referred to within the context of that quote. It is talking about one particular and common use case for the for loop: processing arrays (though I'd say more generally, iterating over a collection of elements). If that is your goal, then the foreach loop is certainly an "enhanced" version of the traditional for loop since it eliminates unnecessary noise.

As others have mentioned, be sure to understand what problem the "enhancement" was trying to solve. If your problem is a natural fit, then the foreach loop with help you. Otherwise, pick a looping construct better suited to the task you are performing so that your code is clearer.
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:Please don't write long lines in your code. I broke a few long lines up for you.

Are you on your phone or on a low resolution monitor?.. The lines render just fine here. I don't have to scroll or anything.
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Ryan McClain wrote:
Thus, one of the reasons I assume it is an improved version of the for loop is the wording.


Well, now that you played with the enhanced for loop, do you still regard it as an improvement. Or is it just a different kind of loop?

Henry

It is a different kind of loop because it is used mainly for reading arrays without caring about indexes.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:Are you on your phone or on a low resolution monitor?.. The lines render just fine here. I don't have to scroll or anything.

Well, it's a good idea in general. It makes your code easier to read and maintain. But yes, the code was scrolling on my monitor before I broke up the lines. It's 1680x1050 which is probably considered low resolution these days.
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:
Knute Snortum wrote:Please don't write long lines in your code. I broke a few long lines up for you.

Are you on your phone or on a low resolution monitor?.. The lines render just fine here. I don't have to scroll or anything.

It doesn't matter that on your device everything renders fine, this is a worldwide forum and everyone probably uses a different device (ranging from high-end to old and probably even very old) to read and post to these forums. So you should be courteous and keep this into account when posting code snippets. Back in the days 80 characters per line was the limit, nowadays I see often 120 characters per line. Don't forget: that guy (or girl) using the phone could have the most awesome answer to your question, but doesn't post because it's too much trouble and effort to have to scroll through all your long lines of code.

My resolution is 1920*1080 and I'm seeing the scrollbar as well. I don't like that (*). Just as I don't like poorly indented code or code with compiler errors. These are all characteristics of poorly readable code. And that's decreasing your chance to get a good answer. The less time I need to decipher your code snippets, the more likely I'll reply to a question.

Just my 2 cents.

(*) That's why I formatted the offending code snippet. See how much easier the code is to read?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!