String[] messages = {"Hello", "Greetings", "Thanks"};
var length = messages.length;
var int i = 0;
for(i = 0; i < length; i++){
System.out.println(messages[i]);
}
What if you want to iterate over a collection, like ArrayList? We will do something like:
Iterator iter = lst.iterator();
for(;iter.hasNext();) {
System.out.println(iter.next());
}
The foreach was introduced to avoid introduction of any new keywords. The foreach introduced in Java 5 simplifies looping further. Let’s take a look at an example of how we can use the new way to loop:
for (String msg : messages) {
System.out.println(msg);
}
You would read
for (String msg : messages)
as "foreach String msg in messages". Within the loop of foreach, msg represents a String element within the array String[].
Instead of inventing another keyword "foreach", Sun decided to use the good old "for". Also, "in" may be used in existing code forfields, variables, or methods. In order to avoid stepping over your toes, they decided to use the ":" instead.
Using foreach with a List
ArrayList lst = new ArrayList();
lst.add(1);
lst.add(4.1);
lst.add("test");
for (Iterator iter = lst.iterator(); iter.hasNext();) {
System.out.println(iter.next());
}
for (Object o : lst) {
System.out.println(o);
}
ArrayListvalues = new ArrayList ();
values.add(1);
values.add(2);
int total = 0;
for (int val : values) {
total += val;
}
System.out.println("Total : " + total);
Can you use foreach on your own class?
You can do that, provided your class implements the Iterable interface. It is pretty simple. For foreach to work, you must return an Iterator. Of course, you know that Collection provides the iterator. However, for you to use foreach on your own class, the use of Collection would have made your class quite bulkier; the Iterable interface has just one method interate().
Pros and Cons:
- Foreach looks simpler, elegant, and is easier to use
- You can’t use it all the time, however. If you need access to the index in a collection (for setting or changing values) or you want access to the iterator (for removing an element, for instance), then you can’t use the foreach.
- Users of your class will not be able to use foreach on your object if you don’t implement the Iterable interface.
Refer to Sun's Java Tutorial for more info.
No comments:
Post a Comment