Class diagram
/** * Custom Collection interface, similar to java.util.Collection * for data storage * @author Stone * */public interface icollection<t> {IITERATOR<T&G T Iterator (); Returns the iterator void Add (T t); T get (int index);}
/** * Custom Iterator interface similar to Java.util.Iterator * used to traverse the collection class ICollection data * @author Stone * */public interface iiterator<t> {bool Ean Hasnext (); Boolean hasprevious (); T next (); T previous ();}
/** * Collection class, dependent on Myiterator * @author Stone */public class Mycollection<t> implements icollection<t> {private t[] arys;private int index = -1;private int capacity = 5;public mycollection () {This.arys = (t[]) new object[capacity];} @Overridepublic iiterator<t> iterator () {return new myiterator<t> (this);} @Overridepublic void Add (T t) {index++;if (index = = capacity) {capacity *= 2;this.arys = arrays.copyof (Arys, capacity);} This.arys[index] = t;} @Overridepublic T Get (int index) {return this.arys[index];}}
/* * iterator ( Iterator) mode, also called cursor mode, provides a way to access individual elements in a container (container) object without exposing the object's internal details. * Iterator mode is to separate the traversal behavior of the collection object, abstract an iterator class to be responsible, so as not to expose the internal structure of the collection, but also allow the external code to transparently access the data inside the collection * * If there is a new storage structure, can be a ICollection, corresponding New a iiterator to implement its traversal */@SuppressWarnings ({"Rawtypes", "Unchecked"}) public class Test {public static void main (string[ ] args) {icollection<integer> collection = new mycollection<integer> (); Add (collection, 3, 5, 8, 3, 3, 5); f or (iiterator<integer> iterator = Collection.iterator (); Iterator.hasnext ();) {System.out.println (Iterator.next ());} System.out.println ("-------------"); ICollection collection2 = new mycollection (); Add (Collection2, "a", "B", "C", 3, 8, 3, 5); for (Iiterator iterator = Collection2.iterator (); Iterator.hasnext ();) {System.out.println (Iterator.next ());}} static <T> void Add (icollection<t> C, t ... a) {for (T i:a) {c.add (i);}}}
Print
35812335-------------abc381235
Java implementation iterator (Iterator) mode