Saturday, May 21, 2016

Enhance for loop in Java part-2

Hello friends, welcome back to Java lover. We all know that we can use object (specially collection classes object) also in enhance for loop. . Not only collection classes object we can also use our own class object in enhance for loop. ( I will write how to create and use our own class in enhance for loop in next post....). So as i said today i am going to write about how how enhance for loop works with objects.

We all know that Objects not works based on index(in the case of List collection also we are calling a function that will return a object. It doesn't List collection having index. List collection internally store data in array that have index. For more details i will write a post related to this very soon...). Only arrays having index. Then the question is how collection objects works with enhance for loop.

Actually we all know that top most interface of collection hierarchy is java.util.Collection. But there is super interface for the java.util.Collection interface, that is java.lang.Iterable. This interface is only responsible for the using objects in enhance for loop(I will tell you mere details about this in next post). Lets see an example:

When ever compiler sees enhance for loop then compiler first identify that there is array or an object. If it is array then compiler convert the code based on index. But if it is an object then compiler convert like this:




Now how many time loop will execute and what data they return is based on hasNext() and next() methods. I will write about these all methods and how to create our own class that will work in enhance for loop in next post... For watching full enhance for loop video on you-tube Click here

No comments:

Post a Comment