The so-called iterator mode, that is, iterator for different containers to provide a unified access mode. This paper takes the container in Java as an example to simulate the principle of iterator. Need friends can refer to the next
1. First define a container collection interface.
Copy Code code as follows:
package com.njupt.zhb.learn.iterator;
public interface Collection {
void Add (Object o);
int size ();
iterator iterator ();
}
2. Defines an interface for a iterator iterator
Copy Code code as follows:
package com.njupt.zhb.learn.iterator;
public interface Iterator {
Object next ();
boolean hasnext ();
}
3. Define a ArrayList, implement the collection interface, and write an inner class that implements the iterator interface.
Copy Code code as follows:
package com.njupt.zhb.learn.iterator;
import com.njupt.zhb.learn.iterator.Collection;
public class ArrayList implements Collection {
object[] objects = new OBJECT[10];
int index = 0;
public void Add (Object o) {
if (index = = objects.length) {
object[] newobjects = new object[objects.length * 2];
system.arraycopy (objects, 0, newobjects, 0, objects.length);
objects = newobjects;
}
Objects[index] = o;
index + +;
}
public int size () {
return index;
}
Public iterator iterator () {
return new Arraylistiterator ();
}
Private class Arraylistiterator implements iterator {
private int currentindex = 0;
@Override
public boolean Hasnext () {
if (currentindex >= index) return false;
else return true;
}
@Override
public Object Next () {
Object o = Objects[currentindex];
Currentindex + +;
return o;
}
}
}
4. Write test procedure Testmain
Copy Code code as follows:
package com.njupt.zhb.learn.iterator;
import com.njupt.zhb.learn.iterator.ArrayList;
public class Testmain {
public static void Main (string[] args) {
Collection C = new ArrayList ();
for (int i=0; i<15; i++) {
c.add ("string" +i);
}
System.out.println (C.size ());
Iterator it = C.iterator ();
while (It.hasnext ()) {
Object o = It.next ();
System.out.println (o.tostring () + "");
}
}
}
Run Result:
Copy Code code as follows:
15
String 0
String 1
String 2
String 3
String 4
String 5
String 6
String 7
String 8
String 9
String 10
String 11
String 12
String 13
String 14
As can be seen from the above, design patterns are used everywhere in the object-oriented polymorphism. interface to call a function in a child class. Click to download source code