The purpose of the Java Container Class library is "Save Object", one is collection, one is map.
But no matter what kind of container class, there must be some way to insert elements and retrieve them ! For example, you can use Add () to insert elements in a list, and get () to remove elements.
But the container class must specify the exact type, such as ARRAYLIST<INTERGER>, but what if you want to use Map/set? How to improve the code reuse rate?
An iterator is an object whose work is to traverse and select the objects in the sequence.
- Using iterator () requires the container to return a iterator. Iterator returns the first element in a sequence.
- Use the next () method to get the next element of the sequence.
- Use Hasnext () to check if the sequence has elements.
- Use Remove () to delete the element that is newly returned by the iterator.
1 Public classMyiterator {2 Public Static voidMain (string[] args) {3Arraylist<integer> alist=NewArraylist<>();4Alist.add (2); Alist.add (4); Alist.add (1);5Iterator<integer> it=alist.iterator ();6System.out.println ("size=" +alist.size ());//output ArrayList original size7System.out.println (It.next ());//using iterators to output the first element of the list8It.remove ();//Delete9System.out.println ("size=" +alist.size ());//output after delete list sizeTen display (it); One /* A * Change to LinkedList - * */ - System.out.println (); theLinkedlist<integer> ltd=NewLinkedlist<>(); -Ltd.add (Ltd.add); Ltd.add (33); - display (Ltd.iterator ()); - + } - Public Static voidDisplay (iterator<integer>its ) { + while(Its.hasnext ()) { A intn=Its.next (); atSystem.out.print (n+ ""); - } - } -}
Output
size=32Size
such as the display () method, do not need to consider the specific type of container, whether it is LinkedList or ArrayList
The display () method does not contain any type information about the sequence it traverses
Java iterator iterator