Podcast Lookup

Java Iterable & Iterator Interfaces Explained | For-Each Loop and Collection Traversal

The Java Developers Hub

  • December 3, 2026
  • 1 h 16 min
  • Episode 29
Episode page
About this episodeTraversing collections is a fundamental operation in Java programming. Whether you're working with lists, sets, or other data structures…
Traversing collections is a fundamental operation in Java programming. Whether you're working with lists, sets, or other data structures, Java provides powerful mechanisms for accessing and processing elements efficiently.In this episode, we explore the Iterable and Iterator interfaces and understand why they are important in the Java Collections Framework.You'll learn how Java uses iterators to navigate collections, how the enhanced for-each loop simplifies iteration, and how to safely remove elements while traversing a collection.This tutorial will help you understand how collection traversal works behind the scenes and how to write cleaner, more efficient Java code.What You'll Learn
  • Understanding the Iterable interface in Java.

  • Why the Iterable interface exists.

  • Understanding the Iterator interface.

  • Why Java introduced the Iterator pattern.

  • How to use iterator() to obtain an iterator.

  • Understanding hasNext() and next().

  • Iterating through collections using Iterator.

  • Understanding the enhanced for-each loop.

  • How the for-each loop works behind the scenes.

  • Differences between Iterator and the for-each loop.

  • Removing elements safely using Iterator.remove().

  • Understanding ConcurrentModificationException.

  • Introduction to ListIterator and bidirectional traversal.

  • Implementing Iterable in custom Java classes.

  • Best practices for traversing Java collections.

Who Should Watch?
  • Beginners learning Java Collections.

  • Computer science and software engineering students.

  • Java developers working with lists, sets, and other collections.

  • Developers interested in understanding Java internals.

  • Programmers preparing for Java technical interviews.

  • Anyone interested in writing clean and maintainable Java code.

Transcript

From the publisher

This transcript comes from the podcast’s own feed, shown as the publisher wrote it.

Java Iterable & Iterator Interfaces Explained | For-Each Loop and Collection Traversal

00:00—
  1. Speaker 1

    Yes, so let's start. Welcome back Coder Army to our Java series. And today we are going to go into a little more depth of collection frameworks. We are going to understand what is an iterable interface and why is it important for us. You will have a lot of fun, you will get to learn a lot in this. So let's quickly go to the screen and start it. Yes, so we know that we saw a hierarchy of our collection frameworks, which was this. First of all, we have the object class, then the iterable interface, then the collection interface, and then the interface of our other data structures like list, queue, set. And we discussed the map that comes out a little bit. From our collection frameworks, right? We all know what the object class is, right? We talked about its methods that it has two strings, hash code, equals, there are many methods. And we also explained them in depth. Okay, let's go and first discuss about our iterable interface. Okay. First of all, let me give you a problem statement. I have a collection. Again, collection can be anything. I have a collection. Whenever I say I have a collection, you can understand that I may have an array list. I may have a link list. We can have a collection of any kind. Or we may have a stack or queue. You know. Or let's say we have a set or map. Right. There can be many types of collections. And my problem statement is that I have to iterate on any collection that you give me. Basically, I have to traverse that collection and fetch each and every element of it. Okay. We know that in our Java collection, we have an array list, we have a link list. And what are these two? They are types of list. And list is an interface. So, if I want to declare an array list in my program, then I can write like this. What can I write? Let's say list, and since we use generics, let's say I'm making an integer list. I'll name it small list equal to new. And here I'll write, let's say, array list. I have to declare an array list. Something like this. Now, again, the question was, do I have to loop through this list? For that, let's say I imagine this list. Let's say I have filled some elements in it. So, I filled 2, 3, 5 in it. 9, 7, 8, something like this. Let's do the indexing, 3, 4, 5. So how many elements are there in total? 6 elements. Okay. So how can we do this? When we enter these elements, there is a method called list.add and we will add the elements one by one. Add 2, add 3, add 5, something like this. And what will the list do? It will fill those elements one by one. Okay. So till now, as much as I know the basic method, how can I iterate in it? Through for loop. Now, because I don't have direct access to this list, I don't have direct access to this array, what I do is, I call some methods on this list. So let's see which methods I call. First of all, I will write my for loop like this, for i equal to 0, I take an int i, and first of all, I put it on 0 as index. And how far do I have to go? I have to go to the last of this list. Now, how can I find the last element of this list or the size of this list? I will have a method, and it is there. I have a method i.isLessThan I can write whatever my name is, list.size It is a size method, it gives me the size of the list So in this case it will give me 6 And I do i + + Simple And now if I want to print my list So here I can write system.out.println And I can fetch one element of my list. How? I can say list.get and here I give index. So I will write list.get i. It will first bring me 2, then 3, then 5, then 9, then 7 and then 1. And I have iterated in my list. Very good. Because I knew that my ArrayList is stored like this from the inside and I can index it and fetch it. So I wrote this method or this code. Very good. Now let's think if my code can work for any container, whether I have a link list, array list, set, queue. Can it? Answer is no. Because we have two types of data structures. Data structures. Which two types? I can't divide it in this part. Those who maintain one data, i.e. maintain ordering. Maintain ordering and don't maintain other ordering. So I'll write not maintain ordering. So this is how I can divide my data or data structures. The ones who maintain the order, I can get an array list, a linked list, any kind of list. Because they have an order maintained. The order in which I stored the data, I can get it back. But the ones who don't maintain the order, they won't maintain the set or the map. Because you know what set and map do? They use hashing. and they store the element where their hash comes. So, we use set and map to find out if an element exists or not in order of 1. We never use them to maintain order. You can think of stack, our queue, they also don't maintain order. In fact, they maintain their own order, we call it LIFO or FIFO. Now, we can think that Q will maintain the order for once. I will give it 2, 3, 5. And when I will take the front element one by one, then I will only get 2, 3, and 5. Because it is FIFA, first in, first out. But overall, I know that I can take elements one by one. But can I iterate on those elements? Assume that I have a Q. Q. I put 2, it went 2. I put 3, it went 3. I put 5, it went 5. Now, what is the way to iterate this? I can't do get i, that bring me i on a particular index. Because I'm not using indexing from inside, right? In queue also, I can just take the starting element one by one. So, if I have a queue.front method, I would have to call it, right? So, what I mean to say is that I have two types of data structures, which maintain ordering a little bit and I can fetch them one by one. That means I have the functionality named get, the functionality named get i. And I get that only in list. I don't get get functionality in set, map, stack or queues. So I can't access everyone with this loop method. So when will this method be useful to me? When I have a list. Okay, one point is clear. Okay, second point. Even if I have a link list. So if I have a list of integer. I will name it list equal to and this time I have a new link list. So you know how a link list works. We know that elements in a link list are stored in the form of nodes. So let's say one is two, one after that will be three, one after that will be four, one after that will be five, something like this. And all these elements are not in contiguous memory location. So there is no question of their indexing. Yes, the array we had, it had indexing inside it. We know there is indexing inside an array, whether it is a dynamic array or any other array. Because a dynamic array is also nothing. You know what it does from inside. It makes a big array as if the previous array gets full. We have understood all this. But in the form of array, we get at least indexing like 0, 1, 2, 3, 4. So when I do get i, here i means that I give an index, let's say I say get me second element. So my compiler can directly jump on the second element. Now why can it jump? Because it has random access. it can fetch the second element directly. But do I get this random access in the linked list? The answer is no. If I do get2 in the linked list, then what is the second element? Is it 0, 1, 2 or 3? It is the second element. But are these the indexes? Are these elements one after the other? These elements are not contiguously present in the memory. It could be in 1000 memory location, it could be in 3000, it could be in 10,000, it could be in anything. We have just connected them with references. So if I do get i, then how unoptimized is this? Think about it. If I write the same loop here, that I write for i equal to 0, i smaller than list dot size And if I try to loop through in this list And if I do list.geti So do you know what will happen from inside? It will happen that I will have a head pointer Which will first give me 2 on this 2 Then I will say get1 Then this head pointer will start again from the front And this time it will give me 3 Then I will do get, let's say 2 will come. Then again my head pointer will start from starting. This time it will go till here, then it will give me 4. Right. Always basically head pointer will start from starting. And will fetch the current element. Current element means the index which I want to fetch. Why? Because I don't have random access in the case of link list. So its time complexity will be order of n square. Right. So this is also a big issue. So I have two issues in front of me. If in any collection, If I want to iterate, basically if I want to iterate one element at a time So, I have two issues. That all collections are not index-based. So, it is not necessary that all collections are index-based. Even our array list is index-based. We have seen that even in link list, the get method exists. The get i method exists. Because link list is a kind of list and this get method comes from our list. So, it exists. But it is very unoptimized. There is no use in using it. I was iterating and I put it in order of n square complexity. So, one problem is that I am not able to iterate in all. So what can be the other solution? If I have to iterate in every collection, there can be another solution. We will think that we know how all data structures work from inside. So whatever the respective data structure will be, the way it will be made, I will iterate that way. For example, if I have Q, then I know how I put elements in Q. I will say 2, then 2 will go in the queue, then 3 will go in the queue, then 4, then 5. Let's say these elements go. And I know if I want to remove elements from the queue, then what can I do? I can remove their front element one by one, right? So I will have some methods for that. First I will get 2, then 3, then 4, then 5. And if I have a stack, then I will get the last in first out. I will put 3, 4, 5, 6 and I will get 6, 5, 4, 3. Something like this. So I will have the methods to remove the top of the stack and the front of the queue. In fact, I have methods that can remove the stack one by one. What can I do? First remove the top, then remove the next top, then remove the next top and then remove the next top. As soon as my stack gets empty, I will understand that I have iterated all the elements one by one. Same goes for queue. But you think, what is the problem with this? The problem with this is that I am tightly coupling my data structure with my iteration, with the logic of my iteration. So, as a developer, I should always know how the underlying data structure works. And secondly, I am tightly linked to it. Now, tomorrow, if someone writes in this statement instead of new link list, new hash set. We know that we have a hash set. If someone writes this, then my logic will fail. I will have to apply some other logic. So basically, there are many boundaries created here to iterate any container or any collection. Now what is its solution? Its solution is Java's Iterable interface. Now let's understand what this interface does. Now if we look at our hierarchy again, we know that the iterable interface comes at the top. Below this comes our collection and below all that comes the list, queue, set, etc. And then below that comes our individual classes. Like if there is a list here, then there will be an array list, link list, set, etc. But the iterable is at the top. Why? Because Java says that any collection which can be iterated which can be iterated it will implement this iterable ok so basically if I write its definition so this is its definition that it is the root interface that represents any object whose elements can be traversed one by one if you want to traverse your elements in any collection or object one by one then you have to implement this interface ok now let's see what is this interface, how it looks, what it gives us let's see one by one Before that, let's understand how an iteration takes place on a collection. So again, to understand that, let's take the example of array list first. So imagine I have an array list. Obviously, it uses an array from inside, so I make that array. And there will be some elements in it, something like this. So, I fill the element. Let's say, here is 2, 3, 4, 7, 10, 9. Something like this. I have filled random elements. And I also write their indexing. So, 0, 1, 2, 3, 4, 5. Okay. So, I am saying that I want such a class. I want such an object. Whichever data structure I have, I can iterate it one by one I don't know how it will iterate, I just call it and it will start doing its work So obviously, if I have an ArrayList So how it will iterate, let's say it will come here first and it will give me 2 Then I will ask for the next element, then it will come here, then it will give me 3 Then I will ask for the next element, then it will come here, then it will give me 4 Something like this Now if you think about it, whatever code is written of the object, which brings me the elements one by one, is it important for me to know how it iterates on the data structure from the inside? The answer is no. That's why I use this class. This is called abstraction. So basically, I am saying that I have an object. For now, I call that object x. This object has some methods that can iterate in this list. So let's see which methods I have in this object. So first of all, obviously if I want to iterate in any data structure, then I should know whether the next element exists or not. It is possible that I am standing here and the next element does not exist. So I should have a method to find out what the next element is. So for that, I have a method hasNext. HasNext. Which tells me, gives me a boolean variable, true or false, whether the next element is present or not. Okay. Now if I want to actually iterate, I will have to bring one element at a time. So there will be one more method in this, next, which will bring me the next element. For example, if my iterator is at the very beginning, I will say next, it will bring me 2, then it will come from here to here, then I will say next, it will bring me 3, it will come from here to here, then I will say next, it will bring me 4, and it will come from here to here, something like this. So I have some methods like hasNext and hasNext which I will call through which I can loop in this array list one by one. Now whether it is an array list, whether it is your link list, whether it is set, whether it is queue, whatever it is, I don't care, I'll just call this unknown object and it'll give me the functionality of hasNext and hasNext. Now let's see what this unknown object is, but I hope you got an overview of how these things work from inside. Now let's go and see exactly what this unknown object is. First of all, any collection that wants to iterate, that wants each element to be fetched, it has to implement the iterable interface. So how will the iterable interface be seen? I am saying that we have this iterable interface. It has a very important method, which is called iterator. Iterator. Okay. So you call this method. It will bring you an iterator. Which will actually iterate in any list or collection. Okay. So iterable interface will bring me an iterator. Then what is iterator? Now in Java iterator is a different interface. In java, iterator is a different interface. Now what is iterator? It is the actual object that will iterate in your collection and will give you each element. So basically this is the one that has hasNext and hasNext. which we just talked about. Okay, I understood that there is an iterable interface and an iterator interface. The method in iterable is iterator, which gives me a reference variable of this. In that, I can do hasNext and nextCall. Okay, so let's first use it and then understand how it works from inside. Yes, so I have made my demo.java as my empty file. And I am going to show you the use of iterators. So let's do one thing first. Let's make an ArrayList. Let's say List of Integer. I'm making a List of Integer. I'll name it List. Equal to new ArrayList. ArrayList. Something like this. Let's import List and ArrayList. Let's import this. Import List. And I'll do the same. Import ArrayList. Both are imported. Okay. Now, obviously, I'll have to add some elements to this list. Let's say, list.add. I've added 10. Okay. Let's add some more elements after 10. Okay, so 20, 30, 40, and 50. So I have an array list of 10, 20, 30, 40, and 50. So you can understand that some elements exist like this. Whatever array is there in my array, and I said that if I want to iterate on this list, then I must have an iterator. Okay. And I had told you that any container or collection that wants to be iterated, it will implement our iterable interface. We have seen that at the top we have the iterable interface, then the collection interface, then the list interface, and below that we have the array list. So if I go inside this array list class, And if I go up and see from where the class is starting, something from here, then it will extend someone. Let's say abstract list. Now what is abstract list? It also comes above the array list, but we don't need to read so much in it. We just go inside it and see that it implements the abstract collection. Let's go inside it and it implements the collection. So here is our collection interface. Okay, as soon as we come inside the collection interface, then you see that it extends the iterable interface. This is the iterable interface that we were talking about. And what did I tell you? This interface has a method called iterator, which gives us the reference variable of the iterator interface, which is a different interface. And on this, exactly that method is hasNext and next, right? Now obviously all of us use generics from inside. So here we have written e and next returns our e. So whatever data type you give it, it will give you the object of that data type. Very good. So we have seen their hierarchy once. And we know that ArrayList comes under the hierarchy of iterable interface. Now because this is a class, so its work is to overwrite all the interfaces on it, basically to provide its definition. So it must have provided the implementation of our iterable interface method iterator. So basically I can write our reference variable list dot iterator. And what did I say, what will it bring me? It will bring me a reference variable named iterator of type integer because it also uses generics. And let's say I call it iterator. iterator equal to list.iterator. Absolutely. Now it is telling me to import iterator too. So I import it. Okay. Now I have imported iterator too. Very good. Now I said that now I can loop through in this list. How? I have method hasNext and next. So now I can do this. I can write while The name of my variable is iterator. Let's call it it. So that there is no confusion with the name iterator. So I write while it.hasNext. Now what is it? You know it is the same which will iterate in this list. So now assume it is standing in the starting of this list. It is standing before 10. And I say it hasNext. Does the next element exist? Yes it does. If it does. So it will bring me the element. So system.out.println I will say it.next Bring me the next element so that I can print it on the screen. Now as soon as I told it it.next Next doesn't just bring me the next element But one position shifts ahead Now my iterator is here Now I will ask again, hasNext? It will say yes. So I will say, bring the next element. It will bring 20, then 30, 40, and then 50. Now as soon as it brings 50, my iterator will come here. Basically, at the end of my array.size. Now hasNext will be false, so it will come out of the loop. And nothing else will be printed. So let's see if my elements are printed. So see, 10, 20, 30, 40, 50, all my elements have been printed properly. So the same thing is happening from inside. This ArrayList must have overrided this iterator method, which gives me an object named iterator. Now you see an interesting thing. Now if I also make a link list instead of this ArrayList. So what I did is, I changed my underlying data structure. We should also import this first. Okay. Let's do one thing, let's import util.star only, so that we don't need to import anything again and again. Something like this. Okay, now we will never get an error. Okay. So, I have changed my underlying data structure. First, I had an array list. Now, I have a link list. I can add elements in the link list. And you know, in the link list, elements don't add after 1. Something like this. 10 points to 20. 20 points to 30. 30 points to 40. And so on. 50 points to 50. Something like this. Okay. But do I still need to change anything in this code? The answer is no. If I run it now, then I still have 10, 20, 30, 40, 50. Okay. Now, interestingly, let's assume that I write collection instead of this list. Because collection is the parent of everything. So, collection and let's say I call it c. Okay. Collection c. So, I can say equal to new link list. Now, I just have to do c instead of this. C. Okay. So, my code should still run. And my code will run. It will run. Because you know that everything is collection. And our iterable comes on top of collection. So, I can call iterator on c too. C.iterator. There will be no problem. Now, why did I do this? I did it because to show this. If I remove the link list and write a hash set, and add some elements to that set, like 10, 20, 30, 40, 50, So now if I add some elements to it, then also I don't need to change this logic. My code will still work. But yes, you can see that I added elements 10, 20, 30, 40, 50, but what was the output? 50, 20, 40, 10, 30. Why did this output come separately? You know that because our set doesn't store elements one by one. It doesn't store like this 10, 20, 30, 40, 50. It stores them on the basis of hashes so that it can store them in an optimized way. So when I So that when I ask from my set that do you have 10, then this answer will give me yes and that answer will give me the constant time of order of 1. So always its order will be very different from the order that I will expect. But the main thing is that my iterator has iterated it. I was able to fetch the element one by one. Now this is not just about the hash set. If I do my array dq pass here, which is a kind of queue, which we will see. Let's put this bracket here again. I added elements in my queue, 10, 20, 30, 40, 50. And you know what queue is, first in first out. So what output should I get? 10, 20, 30, 40, 50. Now I added 10, 20, 30, 40, 50 in my queue. And if I run it, my answer comes back. 10, 20, 30, 40, 50. Very good. Now it doesn't matter. If you want, you can write tree set. Preset is also a kind of data structure. We will read what it does, it implements BST from inside. But here also, I can simply call my iterator and I will get the list. Very good. So how will it be coming? Now let's go and understand its internal, how it works. Now let's see how it works from inside. So basically, we will have something like this that we have an iterable interface. Iterable. Okay. And This is the interface, I have written the class here. So we have this interface. And we have an interface called iterator. And what did we see now? In this interface, there is a method called iterator. This method gives us an iterator object of this iterator interface. And this iterator interface has a method called hasNext. And there is a method called next. We know that hasNext will only tell us if the next element exists or not. And next will actually bring that element. And these two will use generics. So suppose here also it will be T. And here also it will be TType. And this will be our boolean. Something like this. We can assume that. Now see what happens. Now let's see what happens from inside. Let's say we take ArrayList as an example, it will implement this itrable interface indirectly. Why indirectly? Because obviously there will be some other interface on ArrayList and so on. By doing this, we will reach the collection and our itrable interface will come on the collection. So indirectly, ArrayList will be implementing this itrable interface. If it is implementing it, then its responsibility is to give us the definition of iterator method inside it. Now what is the definition of iterator method? It has to return an object named iterator. Now iterator is an interface, you cannot make an object of iterator. That means any other class will have to implement this iterator. Its hasNext and next will have to be overrided. And then it can give its object. Okay. So what it means to say is that suppose we have another class internally. Class ArrayListIterator Let's say ArrayListIterator Let's name it this Which will implement Our this iterator Something like this Something like this Let's make it a little smaller Okay And it will have implementation Is hasNextKey Or nextKey Something like this Now what will be the implementation We will see in a while But there will be some implementation ArrayListItrator implements our iterator interface. So their hierarchy is such that iterator comes at the top and ArrayListItrator implements it. ArrayListItrator. Now what did I say? In our ArrayList class, there will be an iterator method. So let's make this method properly. Iterator. Which it will override. And the return type of this iterator is iterator. Iterator reference variable. Iterator. And here some code will be written. Return new ArrayListItrator. Return new ArrayListItrator. Okay. So, it can do something like this. So, basically, what did it give us? It gave us an object of ArrayListItrator. Now, in that object, I can do hasNextCall, I can do nextCall, etc. Now, when I declare an ArrayList in my code, where I have written list equal to new ArrayList, something like this. Okay. And this type of let's say list will be like this. And when I write list dot iterator, list dot iterator, as we wrote in the code, so as soon as I call list dot iterator, this method will be called from inside. ArrayList iterator method. Which brings us return new array list iterator. That is, it will bring an object of this array list iterator. Now in this array list iterator object, I can do has next and next call. Okay. So what do I do in code? In code, I store its result. Iterator is a reference variable in IT. We know that an ArrayList iterator is an iterator. So, I store it in an iterator. Now, I can call it.hasNext on this IT. And I can also call it.next. Something like this. Right? So I hope it was a little complicated in the beginning. But you must have understood the story. We have a class named ArrayList which implements our iterable interface. And if it implements, then it has to give a definition of this iterator method. So how did it give the definition of iterator? It simply returned an ArrayList iterator object. ArrayListIterator is a class which implements iterator and if it implements then it will give definition of hasNext and hasNext. It has given its definition here. Whenever we write list.iterator, we get the object of ArrayListIterator which we correct in iterator. And in that it, we can call it hasNext or next. And by doing this, in any of our underlying data structure, for example in ArrayList we can loop or iterate. If you're wondering why it's so complicated, first ArrayList implements iterable, then it gives the object of iterator, and then we call a method in it. Why doesn't ArrayList directly implement this iterator? We'll come to that later. But I hope you got a little idea of how it's working from inside. What does it mean to me at the end of the day? It means to me hasNext and next method. So that I can just ask, does the next element exist? And if it does, then bring that next element to me. It shouldn't mean to me what the underlying data structure is. That's why when we changed our code from ArrayList to LinkList, there was no difference in our code. Whether you use Set, Queue, or Stack, you can use any data structure from inside. Every data structure will have HasNext and Next functionality. And whenever I call them, they will bring me the next element. Because the HasNext and Next that will be implemented here will be implemented in such a way that they will know how to remove the next element for that data structure. So that we don't need to know that. We just need to call this method and take advantage of abstraction. Now if you clear some things, then in the next part, everything will be crystal clear when we will see how iterator works. Now we have to see how our different collections implement this iterable or iterator interface. First of all, we will take the example of ArrayList and then slowly we will move towards the rest of the structures. So, if we are going to take the example of ArrayList, then what I do is I make a list of 5 elements and I fill 5 elements in it. Let's say 1, 2, 3, 4, 5. Something like this. Okay. I want to iterate in this list. So, let's see. How will my array list class look from inside? How will its conceptual view look? So, I will write something like this. Class array list. And it will implement our iterable. Implements iterable. So, I have written like this. For now, I am not using generics here, but I want to simplify the code. So, let's assume this is an integer class. Now, what happens in this class? Obviously, ArrayList uses an array from inside. And again, since I am not using generics, let's assume I am using an integer array. So, I have an integer array from inside, let's say arr. So, let's say private integer array arr. I declared something like this. And apart from that, it has its size, so end size. Okay, so I'll private this too. Okay. Now obviously, after all this, it will have a constructor, it will have a lot of methods, add, remove. We don't want to go into all those functionalities. We want to see how it implements the iterable interface. Now if it wants to implement iterable, then it will have to override the methods of iterable. Which method is there in iterable? Iterator. So its work will be to override iterator. So we can write at the rate override. Who is it overriding? It is overriding a method named iterator whose return type is iterator. So I will write iterator iterator. Here we will make it public. Okay. Now let's see how its definition will look. We just saw that this method should work. We have to bring an iterator object. Now iterator is obviously an interface. So whatever class it will implement, bring its object. So it will bring and give us return new Let's say ArrayListItrator. ArrayListItrator. And we discussed that ArrayListItrator itself will have a class which will implement the iterator interface. Now let's come to this ArrayListItrator. But I hope you got an idea of how the iterator method works. Now let's move ahead and see how this ArrayListItrator class will look and work. So I have set my code aside a little here. And we make our ArrayListItrator on this side. So basically what will happen is that we will have a class ArrayListIterator. ArrayListIterator. Which you already know will implement our iterator interface from inside. So implementsIterator. And if a class implements iterator then it will provide a definition of all the methods in iterator. So obviously it will override our iterator method as next. So here it will write public boolean because it will return boolean as next. Something like this. And it will override another method which will be next. So here we will write public integer because I am assuming everything is integer. Next. But generally we use generics from inside. Something like this. Now see, our initial array looked something like this. If I draw my array here, then our array will look something like this. That we had elements 1, 2, 3, 4, 5. Now if I want this array list iterator to iterate one by one on this list, then it should know that hasNext How will it find out if there is an element or not? Or how will it actually give me the next element? Right? So how will it do that? For that, you don't think we need to maintain a cursor inside the ArrayList iterator that where is our initial position now? And now our initial position should be at zero. You can imagine, when we iterate this list in a loop, we used to take index i, first we used to point it at 0, then 1, then 2, then 3, and then 4. Something like this. So basically, here, it maintains that position. So let's say, I tell it, position is equal to currently 0. So int position is equal to 0. Because initially, we will be standing in the starting. Okay, so position is 0. Now, has next. How will it check if the next element exists or not? To check that, we just have to check that whether my current position is less than the size of this list or not. So if I do indexing in this list, then here I will write 0, 1, 2, 3, 4 and what is its size? Its size is 5. You know that whenever I call dot size on the list, what do I get? I get its size. So basically we have to check this method that whether my current position is less than the size of this array or not. So basically what we are saying is that position should be less than Array.size should be something like this. Our position should be less than the array size. So it will work even if it is 0, even if it is 1, even if it is 2, even if it is 3, even if it is 4. As soon as the position is 5, it will be equal to our array.size. That means my pointer will come out. And I will say, bro, false. Next element does not exist. Now here is a problem. This hasNext method, to check that this position is less than this array size, it will have to access the arraySize method. And to access the arraySize method, I will have to put the object of this arrayList inside it. Right? So it will be very complicated to put the object of this arrayList inside this arrayList iterator. And what will this arrayList do? It will give me the object of this arrayList. Here, our very good work will come of nestedGlasses. What will happen? I will put this arrayList iterator If I put this array list inside the class, after that, it can access this array, it can access this size too. Basically, it can access all the private members of this array list. I won't have any problem that I have to pass objects. Right? That's why we had brought the concept of nested class. Okay, so let's do one thing. Let's assume that This entire class comes inside this class as an inner class. See, just like this. What we did is, we put the ArrayListRiterator class inside our ArrayList class. Now, it can access these private members too. So, now, I just have to write this hasNext code as return. What do we have to return? That is, is the position less than our This size can directly access the variable. Position is less than size. If it is, it will return true or false. This is the implementation of hasNextName. How will the implementation of hasNextName take place? Now, what will the next method actually do? It will return whatever is my next element and will shift the position variable to the cursor. So, I can't write anything like this. I can write something like this. First of all, let's take an integer. Let's say x equal to my current position. So, array of pos. So currently my position is 0, so what will be the array of 0? 1. So I will get 1 in this x variable. And then I will do pos + +, 1 position plus. And return x. Something like this. Now by optimizing these three, can't I write like this? If I directly write, return arr of position + +. Something like this. So what did it do? It also gave me the current arr of position. Because this is postfix notation, so it also gave me 1 first. And also made the position an increment. So it gave me 1 first and then our position shifted here. Right? So this is the kind of implementation that happens in our ArrayList. When we say hasNext, it checks if our current position is smaller or not. And when we say next, it gives me the array of current position and increases the position by 1. Now, you know how I will iterate this. I will simply write in my main function, let's say my main is I will write here that I want an iterator object, let's say it equal to, let's say I have a list, I call it list, so I will write list dot iterator, I will call its iterator method, as soon as I call iterator, this method will be called and what will it give me? This array list iterator, that is, it will give me an object of this inner class, which I will store in this it name variable, and now I will write from inside while it dot has next, and As soon as I write this, what do I do from inside? System.out.println. Right? Now as soon as this loop executes, let's see what will happen. First of all, it will call it.hasNext which means this method will be called. It will check whether my current position is less than size. Current position is 0. Is it less than size? The answer is true. So it will return true. Which means I entered the loop. Now as soon as I entered the loop, I called the method it.next which means this method. and it.next will bring the position element of the internal array and make the position plus plus. i.e. i will get this element on the screen, i.e. 1 is on the screen. Then my position has come from here to this element. Then again, it.hasNext will implement it. The current position is 1. The answer is true. Then I will do it.next and I will get 2. I will write 2 on my screen and my position will increase again. And this will keep happening. Then I will get 3, then 4, then 5. And finally, my pointer or position will come here. Now, as soon as it comes here, that is, the value of the position is 5. We will check whether 5 is less than or if the answer is false from 5. We will come out of this loop and our whole array will be printed. I hope you understood how the whole thing works from inside. Now, if you understood about the array list, then you can think for yourself how the link list implemented its iterator. Let's see that too. Now see, we know that the link list works on nodes. So let's say one node is 2, the next node is 3, the next node is 4, the next node is 5, something like this. This is not random access, in this I can return some array of position + +, right? Because this is something from inside, it uses node from inside. So if I try to implement my linked list class, then let's say I write linked list and it will also implement my iterable interface. Something like this. And we know, what does a linked list do? It makes a class from inside itself, a node class. So we have a class called node, and it has two things. One is data, so let's say I'm just assuming an integer, and one is this node reference variable next. Something like this, right? Now we know that this class is a static class. So I can write static here. Because I don't want to make it an object. I have made a static class node here. And apart from this, it must have a reference variable named node. Let's say head. Which points to my starting of the list. So let's say head will be here in my starting. And again same. This is my linked list class. It implements iterable. So it will have to override. It will have to override our iterator method. Iterator. Which will do what? Which will return. an object named iterator. And what is iterator? It is an interface. That means somewhere this iterator will be implemented by someone else and this object will be returned. That means it will do some return new link list iterator. Like our array list iterator, it returns link list iterator. Something like this. Okay? And obviously, what will this linked list iterator be? It will be the same class which implements the iterator and implements its hasNext and next. So, there is no space here. So, let's see how our linked list iterator will look if I make it here. So, let's make it a little smaller. You can assume that this linked list iterator is inside it. So, this code is inside it. So, something like this will be written. Class. So, linked list iterator implements iterator Now if it is implementing the iterator, then it will have to override our hasNext first. So let me write boolean hasNext. And it will have to implement. And let's say it will have to implement next. So I write next here. Something like this. Now you think, how this linked list iterator will iterate in this list? To iterate, we need a reference variable which will be in the starting and will go ahead one by one. Now because this linked list iterator class exists in our linked list class, it can also exist in this node class. So I can say that it has something written here, a reference variable named node. And let's say I call it current. And it will point to our head. Where our head is, here will be our initially current. Right at the starting. Now you know how I can check the next in a link list. I just have to see that my current is not pointing to any null. Because current is pointing to this. Then current will point to this next time. And next time it will point to this. And next time it will point to this. And then when I will tell it to point to next. Then our current will come out. That means it will be pointing to some null. So I just have to check return. Current is not equal to null. If current is not null, it means it is pointing to a node. It means next element exists. Right? Okay, so we understood how to have next. Now, how to work next in the linked list? You know it. All I have to do is return the data of current pointer. And increase the current pointer. So, first I take the data in int. its data is current.data so as soon as I call current.data what will I get? 2 so I have stored it in integer and then I will do current in front so current equal to current I will write it here so that you can see current.next something like this now as soon as I did current.next my current shifted here current shifted here and it moved from here and finally what can I do? I can return my data Something like this. So basically, my implementation will come up to here. Right? This way, I can also implement my next. So now when I will write code in my main method, same, that while it.hasNext keep calling me, It.next. Right? We write this code. So, do you know how the code will work? First of all, we will go here in the starting. It.hasNext is true. The answer is yes. It.next. We will get 2. And our current will shift here. Then we will get 3. Our current will come here. Then we will get 4. Then the current will come here. And then finally we will get 5. And our entire linked list traversal will be possible using this. Right? So we understood how the iterator of the linked list works. Now we have seen the array list, linked list, you must be understanding the benefits of this. What every class has done is implemented its iterators, that how their has next and next will be called. And all we have to do is call that iterator. We don't care which underlying data structure is used, we can just iterate in it. Now we can think about how the set and the map work from the inside. Now, what do the set and the map work on? They work on the basis of hashes. That means, they don't store the data in an ordered fashion. So, basically, how will its iterator be written from the inside? Maybe its iterator travels bucket by bucket. So let's say this is a bucket B1, this is a bucket B2, this is B3, this is B4. And we know what happens in every bucket, there is some value. Now here if it would have implemented chaining, then there would have been multiple values in one bucket, right? We saw this too. So it is possible that its iterator goes from inside bucket by bucket and element by element. So first of all, the first element of the first bucket, then its second element, then the first element of the second bucket, then its second element. Something like this, right? Same, you can imagine that we have a tree set or a tree map, and what do we implement from inside? We implement BST, Binary Search Tree from inside. So if I call its iterator, then it might give me an in-order traversal from inside. Right? And the same goes for our queue or stack. We know how queue and stack are implemented from the inside. They are using arrays. I can call it an array list. So if they are using an array list from the inside, then their iterator can give me an element of the underlying array. Just like we did in the array list. Now after learning so much, let's make our own iterator. We will make our own class of a collection type and see how we can implement our own iterator in it. So here I have made a file by doing demo2. java and our job is to implement our own iterator. So that we can understand things better. Now because we want to make a collection of our own, we want to make a class of our own which will work as a container. Meaning it will hold multiple things. So let's say I want to hold a lot of names. So I can write a class, let's say name container. Something like this. NameContainer holds a lot of names. So from inside, I'll use an array of strings. So string array, let's say I'll call it arr. And I'll keep it private for now. And I'll keep its size. So private int size. Something like this. Now I'll give this nameContainer to our constructor. Which will take, let's say, an array of strings from me. So string array ARR and I'll sign it in this array so this.ARR equal to ARR something like this now instead of this ARR we'll write names because this is an array of names so names sound better Let's do names here and here as well. Okay? Now look, my name container is using an array from inside, right? So it should also have a lot of methods. So getName can be there, or setName can be there, or you must have understood that let's say I want to insert a name somewhere in between, so insertName can be there, replace can be there, a lot of them. I can give a lot of methods. But again, we are not talking about those methods, we have to implement iterator, right? So let's say I write here first, implements iterable, I can do this. Since it uses generics, I will write string here. Because I am using string from inside. So implement iterable interface using string. As soon as I got an error, the right name container must implement the inherited method. So now let's go and overwrite the iterator method of this iterable. So I will write at the rate override public I have to return an iterator object. iterator of type string and the method name is iterator. Something like this. Now, what is iterator? You know that it is an interface. I have to return an object. So, I have to override this iterator. I have to implement it through the class. Now, I have to do one more thing. First of all, I have to import this. Now I have to return an object named iterator and iterator itself is an interface which means a class which will implement this iterator and will override its method and its object will return a new name container iterator Iterator. I have to return its object. I haven't made this class yet. So now let's go and make this class. And what I said is, how will we make this class? As a nested class. So I keep this as a private. Because I know, I don't want to give access to this nested class. I have to keep this class private. So that it can work with these variables. So private class name container iterator. Okay, something like this. And what does it do? It implements iterator interface. Iterator using string. using string. Something like this. Okay. So, see, I got an error from here. No problem. Now, an error has come here. Because if I have implemented iterator, then I will have to override its methods. So, first of all, which method comes to me? HasNext and then next. So, first of all, I will overwrite my hasNext method. So public boolean hasNext something like this. And I will write it here at the rate override. And I will overwrite another method whose name will be our next. And what will be its return type? Obviously, it will be string type because we are working in the entire string. So, something like this. Now, because it is a private class, it has access to these private members. Now, what did I say? In an array, how can I check hasNext? For that, I need a position. So, I work int pos position equal to 0. I keep it like this. And this is my private variable. So, I make it private. Now, tell me how hasNext will be implemented. It will return. Whatever our position is, it should be less than this. From the length of this array. What is the length of this array? Here, size is written. So, position should be less than size. If this is true, then hasNext is true. Otherwise, it is false. Now, I have not declared size here. So, I will do it here. Let's say this.size size equal to this.names.size names.length inside that we have length property something like this ok now I have to implement next and how will I get next element we know we can write simply return our The name of the array is names of POS + + Something like this. We saw this in the array list. Now I don't get any error. I made a name container class which implements iterable. I wrote a method named iterator which will return my name container iterator. And this is my name container iterator class which implements iterator. And here is its method hasNext and next. Okay. Now let's go to our main class and see how we can use it. So I can write, let's say name container, an object, let's say container equal to new name container, something like this. And here I have to pass a string. So first I do one thing, I make a string of names. So string names equal to, and let's say I give them directly here. One is named Aditya, one is named Rohit, One is named as Rohan, the other is named as Monu, something like that. We have given a lot of names and we will pass these names here. Now what I have to do is call the iterator of this container. So I can do it like this, iterator of string. I will get it equal to container dot iterator. Okay, so I must have got the iterator. Now what I have to do is just loop through here, while it dot has next What I have to do is print on the screen system.out.println It.next Something like this And I am expecting all my names to be printed on the screen Aditya, Rohit, Rohan, Monu. My method is correct. My code is correct. Now, I can do some optimization in this. Should I return new name container iterator and create an internal class? I know that this internal class will never be used again. It has only one use. After this, it has no use. It just has next and overwrites next. I don't have to change it again and again. And we know that we can replace a class that is used only once using anonymous class. So what happens if I make an anonymous class here instead of return new name container iterator? What does it mean? I simply write return new iterator and open the code of my anonymous class here. And I declare all these methods that I made here here. Something like this. Okay, I didn't get any error. Now I can remove this nested class from here. Something like this. So now see how small my code has become. I have a name container which implements iterator and how it implements? Through anonymous class. And if I run it now, then I should get the same output. Aditya, Rohit, Rohan, Monu. No problem. So I can do this too. Now we understand a problem that the code of iterator is a bit complicated. First I will write container.iterator, I will take an iterator variable and then I will run the loop it.hasNext and then it.next. It is a very verbose code. So Java also thought that it is verbose. So Java gave us a new thing which we call enhanced for loop. Its second name is for each loop. Right? You must have seen this many times. We use enhanced for loop many times. But we never knew that enhanced for loop is nothing else. There is a sugar coating on our iterator code. So basically, I can write like this. Let's say for string name in our container. This is my container. And what can I simply do? System dot out dot println and here I can write name something like this now if I comment it like this then also my code will run see if I run it then see aditya rohit rohan monu is still printed right this means that my enhanced for loop when I write it like this then compiler converts it from inside to this code because this code is very verbose So you can write like this or like this. This code goes to JVM from inside. So there is no enhanced for loop, there is a sugar coating on it. So if you want, remove it. Now see how clean our code is looking. We just wrote string name in container system.out.println name. Now to prove that this enhanced for loop is nothing, but it converts from inside like this. I do one thing, I remove the code of this iterator from inside this class. And I also remove the implements. So now our name container has become a simple class. In which there is an array named string names. And there is a size variable in it. And what we have done in our constructor is that we have taken an array of names. And we have added it to our names. Simple. And I am not doing anything else. As soon as I do this, I will get an error here. And what will be the error? Can only iterate over an array or an instance of iterable. I will only be able to iterate if you give me an array. Or if you give me an instance of iterable. That's why my code won't work. I have to write this. Implements iterable. And I have to overwrite iterator. Now my code will work. So if you understood all this. Then I have to tell you some more things. This was our iterable interface. Iterable. And the second was iterator. Now we have to see what are the methods in this. Till now we have talked about only one method of iterable. Which was iterator. And you know what it does? It gives us an object named iterator. It is an interface itself, so it gives us the object of whatever it implements. Apart from this, it has two more methods. One is forEach and the other is splitIterator. Okay. Now this forEach, we will read it when we are reading the functional interface. Because we will understand it only when we use lambda expressions in it. Which we haven't read yet. And splitIterator is an advanced method. Which we will understand only when we will understand streams. So for now we ignored these two. And we understood only one method which was iterator. Which gives us an iterator. Now this iterator class, we saw that one is hasNext. One is next. We have seen these two methods. Apart from this, it has another method called remove. That means you can remove an element from any list or container. So when you write something like this, iterator it equal to let's say list dot iterator. You write something like this. You call its iterator method. You get iterator it. And then you write while it dot has next. And inside this you write print it.next something like this while doing this you can also call it.remove and one of your elements will be removed which element? like we had a list 2,3,4 your it is here you said it.next you moved forward it came here now when you write it.remove your last element will be removed from this list so you can also do this we also have a function called remove in iterator Now if we have remove, then why don't we add it? We can add an element too. But is it that simple to add an element? If I have a list of elements, let's say 2, 3, and 4. Now think, if there was a method called it.add, and I am in a list, let's say I am here, and I have written it.add, then you will say add an element in the middle, let's say 5, then my array will be 2, 3, 5, 4. What is the problem? You don't have any problem here. But think about it. Who implements iterator? Who implements the class in which iterator exists? Right? So think about it. If this was our list and there was a set. And you know that value can go anywhere in the set. But you are standing here. IT. And let's say you wrote IT.add. And you added 1. So it is not necessary that one should be added after this element. It is possible that it should be added before. Its hash should come out like this that it should come here and be added. But your IT will never be able to print it because your IT has gone ahead. Or it has come ahead of that bucket. So the functionality of add will become very complicated in any iterator. That's why it was not kept there. Right. So I hope you understood this too. Now if you want addNum functionality, then you will get it in list iterator. And where is list iterator? It is inside the list. We will see that when we will understand the list interface well. But for now, you understand that these are just three important methods. Apart from this, there is one more method, which is called forEachRemaining. Like here is forEach, here is forEachRemaining. Again, we will read this when we are reading the functional interface. Okay? Now I have taken a file called demo3. java because here we are going to understand a new concept which we call concurrent modification exception. Now what is concurrent modification exception? Let's make a list of integer. Let's say list equal to new ArrayList. Like this. Okay. Now again, I had to import it in ArrayList. That happened automatically. Now let's import this list as well. We have imported it as well. Okay. And let's do one thing. Let's simply import util.star. We don't need to import anything else. You know what star means. Import all the classes of that package. Okay. Now what did I say? Let's add some elements to this list. Let's say 1 added. 2, 3, 4, 5. Let's add some more. Let's say 2, 3, 4, 5. Something like this. I have added elements from 1 to 5. Now you know how we used to write its iterator. We used to write iterator it. We will get it. How? When we call iterator method on this list. It will give us an iterator. And again, what type of iterator will this be? Let's say this will be our integer type. Integer. Okay. And what can I do? I can loop through on this integer. So while it.hasNext. System.out.println Okay, something like this And if I run this code Then my elements will be printed from 1 to 5 Very good Now let's say I wrote some code here I didn't directly print it I took its value in int first int value equal to it.next Something like this And I wrote that if value is equal to 3, then you do list.removeValue. Let's say something like this. List.removeValue will remove this 3 from this list. Something like this. And let's say after this, when all this is done, then I will print system.out. println, my value, something like this. Okay? Because I have already connected it to value. I have checked that this value is equal to 3, so remove the list. So now see what will happen here. I said that when I am traversing in this list using my iterator, I have changed that list, modified that list. If this happens, then my iterator will say that I cannot loop through in this list because this list has been overrided, this list has been changed. Okay? So when I run this code now, So I will get an exception whose name is concurrent modification exception. And see when it came. It printed 1, 2, 3. My value must have been printed correctly till here, right? After that, this if statement must have been run that if the value is equal to 3, then remove it from the list. As soon as I removed it, My iterator found that my starting list has changed. And if it changed, then it threw me an error. Concurrent modification exception. I can't work on this list anymore because it has been modified. I don't know which element is missing. Have I iterated it or not? etc. etc. In the list, you might find it simple to hear that it iterated till where it went. But imagine in the case of set. Elements can be removed from anywhere in the set. They can come anywhere. So maybe it printed it but you removed it. So understand what the problem can be. iterator will not know how to deal so iterator gives concurrent modification exception we call this fail fast whenever you feel that list has changed fail yourself rather than assuming things it is safe Now you must have a question in your mind that why so much delay? First of all, any collection will override or implement this iterable interface. And this iterable interface will give you an object of whose? It will give you an iterator. The iterator itself is an interface. That means it will also override something. If I give an example of a list, then we saw let's say array list iterator. There will be a class which will overwrite it. So I will write that this is our interface. This is also our interface. And we have extended it from a class. Let's say ArrayList. Something like this Generally there is a method called iterator in ArrayList And that method comes from our parent interface iterable And this iterator gives me the object of ArrayListIterator And on that object I can call as next, next or remove There is no problem But why so much delay? Can't I directly implement ArrayList through iterator? What if I write class ArrayList in my code? Let's say ArrayList implements iterator. If I directly write iterator, what will be the problem? Now the work is not easy. I just have to give the implementation of hasNext. My work will be done. Now, look at one more thing. Here, I just say, give the implementation of hasNext and next. We never give the remove because we can give it or not. It is always our default method. That means, it is declared in the iterator interface. It is defined, basically. So, if we don't give it, then it will be fine. We just need to give the implementation of these two. Okay. So, if I have to do this, then my work will not be easy. Absolutely not. There will be a very big problem. Okay. What is the problem, brother? Look. Look. First of all, I will tell you a small problem. That is, separation of concerns. Okay. Separation of concern. We want our code to be clean. And one class has only one responsibility. We read this principle in low level design. When we read about solid principles. Which we call single responsibility principle. That one class has only one responsibility. So, I am saying that our array list or link list or set, hash, set, whatever data structures we have, their work should be to store data. Right? How do we access this thing in data? Basically, our collections should focus on only one thing, on data storing. Something like this, right? It should not focus on how to move on the next element. If it implemented iterator, then it will have to focus on hasNext or next. Now think, why do we need to implement iterator also? What if I remove this too? Because if I define hasNext and next in this, So why would I want an iterator interface to come from above? Right? I would want it for the same reason. So that separation of concern remains. Container or collection work should be done of data storing. And there should be the responsibility of another class to move that data. Now how will that movement happen? Iterable says that any class that can be iterated, it will implement me. So any class that is iterable, it will implement me. And what will I do? I will give a method in it, iterator. iterator. As soon as you call that method, you will get your iterator. Use that iterator and iterate in your container. Okay? Now, okay, we understood this. But let's say I don't have much focus on this separation of concerns. No problem. There are has, next and next in iterator. I will directly implement iterator and if I do its has, next and next override, then I will override it. Why do I need iterable in between? Now comes the second reason which is very important. More than our code looks clean because error will come here. And what is that error? So to explain this problem, I again wrote a code, myArrayList. And I declared all the methods as next and next in this. I said it doesn't matter, I don't care about separation of concerns. I want my array list to store the data and iterate in the data. It should work by itself. So I didn't take any iterable interface here. I thought what's the use if I'm defining everything in this. So why do I need such an interface? I defined hasNext and next in this. And my thought here is that any container will have its own work to implement hasNext and next. Right? So that I can iterate in any container. Now see what will be the problem. Here I took an array named position internally which stores 10, 20, 30, 3 variables. I showed it here. It has a size of 3. And as you know, if I want to iterate in this, then I would need a position, current position which is at 0. And the rest hasNext and next is a very simple implementation which we saw earlier. What will hasNext do? If position less than size, then return true, otherwise return false. And what will next do? In this array, here I have written position, this is wrong. Its name is arr. Its name is arr. Yes. Now what I did here is that I returned arR of position + + which we saw in the array. Now the first problem here is that if my position gets updated once, then how will it be set back to zero? So basically, if I made an object of my array list, let's say my array list, an object called l equal to new my array list, suppose I declared that and suppose if I want to loop through this list, then I will write while l dot has next And here I will do system.out.println. So as soon as I have written this code, everything will work till here. So first of all, my position will be at 0. I will say l.hasNext. The answer will be yes. I will print 10 and move forward. Then I will print 20. Then I will move forward. Then I will print 30. Then I will move forward. And finally my position will come here. here. This is 0, this is 1, this is 2 and my position will come on 3rd. And if it comes on 3rd then l.hasNext will be false. I will come out of this loop. So this loop is done. If I want to iterate in this list again, can I write this code again? while l.hasNext Can I write this again? and then write l.next in it? The answer is no. Why? Because my internal position variable has changed to 3. Right? So, my hasNext will always be false because it will try to do 3 less than 3 which is always false. We will never enter this loop. So, this is the first problem. Now, to solve that problem, I have to give one more method here. So, let's say, I will call it voidReset which will reset my position again. So, position equal to 0. It will set something like this. Okay. So, this problem is solved. That means, before this, I will write, let's say, l.reset. Okay? So that my position gets reset. So now this code will also work. Okay, the first problem is solved. Now look at the second problem. Now for that I will remove this code. The second problem comes with nested loop. Suppose I have to print it nestedly. So I have written some code like this. So I will write, let's say my l variable is equal to new my array list. Something like this will be written. And in this I will write first of all l.reset so that I can reset the position once. My position is at 0. So first I will tell you how to print it. So I want to use nested loop. I want for the outer loop, for 10, first 3 elements should be printed. Then 3 elements should be printed for this 20. And then 3 elements should be printed for this 30. Means something like this should be printed. 10, 10, 10, 20, 10, 30. And then 20, 10, 20, 20, 20, 30. And then you would have understood 30, 10, 30, 20 and 30, 30. Something like this. So I will write some code like this, I will write while it.hasNext Right, I checked that it.hasNext is there, it will say yes because my position is here right now Whatever my variable will be, I will take it in an a variable, let's say So it will not come here, it will come here, l.hasNext right And now whatever my variable will be, l.next, I will take it in my a variable named a right So in my starting, 1 will be 10. Now for this 10, I have to run an internal loop again. That means I have to run an internal loop again. Something like this. L dot has next. And I will do something from inside int b equal to l dot next And then on screen I will print a comma b both I am expecting And you know as soon as I will write a loop from inside My position name variable is only one This will start moving only in position So I wrote a equal to l dot next I got 10 in position And My position will be updated from here and it will be increased from here. So, 10 is in A. Very good. Then my internal loop ran. It checked if L dot has next. It will check if there is another element. And it will do L dot next in B. That means 20 will come in B. That means 20 will come in B. And the position will increase from here to here. And I will print A comma B. That means I have printed 10 comma 20 on the screen. But my position has already moved till here. Now when I again I will loop through again in the internal loop I will check if L.hasNext is correct and then I will print L.next in B My position will come out and my 30 will be stored in B And I will print 10,30 on the screen So first 10,20 was printed then 10,30 And after this, nothing will be printed. Even though I have a method called reset, even if I reset here, my desired output will not come because then my position will be reset. That is, the position will come in the starting for my outer loop. So you understand the problem. If we ask the same container to store the data and give me the output one by one, then it will never be able to give us the access to multiple loops from inside. Because the position that manages the state is the same variable. Now you will say, let's keep multiple, but how much will you keep? It is possible that I will use 2 loops in nested, 3 loops, 4 loops, right? So it will be very problematic. So what is the inner loop doing? It is also changing the positions for the outer loop. This code will become very complex. And you can't do anything here because you wrote all the logic inside the container. That's why Java introduced the concept of iterable. That we will have one iterable, one iterator. And your class will have to implement an iterable Which will give you an object named iterator In that case, we didn't put this position variable in myList But we put it in a nested class whose name we used to put ArrayListIterator And we put this position in that class Now see how much freedom we have If we want to use a nested loop So we have to write L.iterator again. Now we can keep multiple iterators of the same container. The upper iterator will be different and the inner iterator will be different. Because whenever we call L.iterator, we will get a new iterator. Not that we are going to an old iterator. In this normal case, we can't create multiple iterators. We can only create multiple ArrayList objects. And if you change the object, then its container also changes. But now you will say that our 10, 20, 30 is declared inside. So make its object O1 or O2. This list will come in both. It will come. But it will come for this case, right? But our ArrayList, LinkList, we can do L.Add from outside also. Okay? So you must be understanding the problem that we are trying to iterate in two different objects at the same time. And we always want the container of both the objects to have a similar element. So that we can do this work of nested loop. This is why separation of concern comes. That we separate the logic of iteration and the logic of storing. So that if someone wants to iterate, he can directly say bring me an iterator. Get an iterator and iterate with it. This means that now every iterator will be unique. Whenever you write list.iterator, you will get a new iterator every time. In list interface or any interface You will always get a new iterator But whatever iterator you get Let's say IT You can do anything in it You can do normal loop in it You can remove some elements Using IT.remove Right You can do anything I hope you understood everything well What is an iterable interface How does it work That's all in this video Now we will see collection interface in next video We will meet you in next video Till then Thank you so much