This article mainly introduces the collection and iterator interfaces.
First, Collection and the Iterator Interface
Collection interface is List , Set ,, Queue the parent interface.
Collection C = new ArrayList ();
The parent class points to the child class Object! Advantages: Multi-state, dynamic link, upward transformation.
Interface-oriented programming, the caller is completely transparent to the caller, you can arbitrarily replace the subclass, shielding the subclass unique things.
Demo : Please attend: Java API documentation
Second, how to loop through the elements in the collection in turn?
Normally , when we "throw" an object into the collection, the collection forgets to change the object's data type, and the default is object. after JDK1.5, you can restrict and remember the type of the elements in the collection by using the generic type.
- iterator iterator OL type= "1" style= "margin-left:0.375in; direction:ltr; unicode-bidi:embed; margin-top:0in; margin-bottom:0in ">
-
- Provides a unified access interface
- < Span style= "Font-family:microsoft Yahei; font-size:14px "> difference: iterator for accessing objects, collecton for holding objects
public class Testiterator {public static void main (string[] args) {Collection books = new HashSet (); Books.add ("Englishbook "); Books.add (" Computerbook "); Books.add (" Musicbook "); Iterator booksiterator = Books.iterator (); while ( Booksiterator.hasnext ()) {String book = (string) booksiterator.next (); System.out.println ("book:" +book), if (Book.equals ("Computerbook")) {booksiterator.remove ();// The following code throws an exception: Concurrentmodificationexceptionbooks.remove (book);} Book= "Just a test!";} SYSTEM.OUT.PRINTLN (books);}}
Output Result:
- foreach , simple to use
public class Testforeach {public static void main (string[] args) {Collection books = new HashSet (); Books.add ("Englishbook" ); Books.add ("Computerbook"); Books.add ("Musicbook"); Iterator booksiterator = Books.iterator (); For (Object object: Books) {String book = (string) object; System.out.println ("book:" + book), if (Book.equals ("Computerbook")) {//books.remove (book), book = "Just a test!";}} SYSTEM.OUT.PRINTLN (books);}}
Output result :
Three, compare two kinds of traversal mode:
The same point: when iterating over a collection element in a loop, the system simply assigns the value of the collection element to the iteration variable. And the set itself does not change
Difference:
1.foreach more Concise
2.Iterator is powerful and can operate on the elements accessed during the loop
A big wave of Java Strikes (vi) collection and iterator interfaces for the--java collection