Set [iterator, enhancement for, generic],

Source: Internet
Author: User

Set [iterator, enhancement for, generic],

Java. util. Collection Interface
Is the top-level interface of the Set, and defines the common methods of the set.
The interface cannot directly create an object. The object is created using polymorphism.
Collection <data type (generic) in the Set> coll = new ArrayList <data type (generic) in the Set> ();

Iterator
The methods for storing data in a collection (data type) are different, and the methods for retrieving elements in the collection are also different. java provides us with a common method for retrieving elements, called the iterator.
Interface describing the Iterator: java. util. Iterator

Abstract methods in the interface:
Boolean hasNext () returns true if there are still elements that can be iterated. Whether there are any elements in the collection, true is returned, and false is not returned.
E next () returns the next element of the iteration. Extracts the next element from the set.

The iterator is an interface and the implementation class of the iterator needs to be found. The implementation class of the iterator is the internal class of each set.
There is a method in the Collection interface: The iterator method returns the iterator
Iterator <E> iterator () returns the Iterator that iterates on the elements of this collection.
The ArrayList set implements the Collection interface and overrides the iterator method. The return value of the method is the implementation Class Object of the iterator.

Note: you only need to know which implementation class object is returned by the iterator method but the implementation class of the iterator. This method is called interface-oriented programming.

Steps for using the iterator:
1. Create a collection object and add elements to the collection.
2. Use the method iterator in the set to obtain the implementation Class Object of the Iterator, and use the iterator interface to receive (polymorphism)
3. Use the methods hasNext and next in iterator to iterate and retrieve the elements in the set.

1 public static void main (String [] args) {2 // 1. create a Collection object and add element 3 to the Collection. // Collection <String> coll = new ArrayList <String> (); 4 Collection <String> coll = new HashSet <String> (); 5 coll. add ("Yao Ming"); 6 coll. add ("Jordan"); 7 coll. add ("James"); 8 coll. add ("Kobe"); 9 coll. add ("Iverson"); 10 // 2. use the method iterator in the set to obtain the implementation Class Object of the Iterator, use the iterator interface to receive (polymorphism) 11 // What is the data type in the Set, and what is the data type of the Iterator, follow the 12 Iterator <String> it = coll. iterator (); 13 // 3. use I The Methods hasNext and next in the terator are iterated to get the element 14 // boolean hasNext () in the set. If there are still elements that can be iterated, true is returned. 15/* boolean B = it. hasNext (); 16 System. out. println (B); 17 // E (String) next () returns the next element of the iteration. 18 String s = it. next (); 19 System. out. println (s); 20 21 B = it. hasNext (); 22 System. out. println (B); 23 s = it. next (); 24 System. out. println (s); 25 26 B = it. hasNext (); 27 System. out. println (B); 28 s = it. next (); 29 System. out. println (s); 30 31 B = it. hasNext (); 32 System. out. println (B); 33 s = it. next (); 34 System. out. println (s); 35 36 B = it. hasNext (); 37 System. out. println (B); 38 s = it. next (); 39 System. out. println (s); 40 41 B = it. hasNext (); 42 System. out. println (B); // false, no element 43 s = it. next (); // if no element exists, the NoSuchElementException will be returned if no element exists. 44 System. out. println (s); */45 46/* 47 * It is found that the above iteration process is a repetitive process. You can use loop optimization 48 * we do not know how many elements are in the set, so you can use the while LOOP 49 * while loop end condition: hasNext (); returns false50 */51 while (it. hasNext () {52 String s = it. next (); 53 System. out. println (s); 54} 55 System. out. println ("-------------------"); 56/* 57 * for loop type Iterator, using 58 */59/* for (Iterator <String> it2 = coll. iterator (); it2.hasNext ();) {60 String s = it2.next (); // retrieve the element and move the pointer to the next 61 System. out. println (s); 62} */63}

An error occurred while modifying concurrency.
When the length of the set is modified during iteration, a concurrent modification exception occurs.
During the traversal process, the length of the set is modified, but the iterator does not know, it will produce ConcurrentModificationException

Solution:
1. iteration is iteration. do not modify the set.
2. Use the add/remove Method in the ListIterator sub-interface of the Iterator to allow the Iterator to add/remove elements to/from the set.
In this way, the iterator knows the changes in the Set, and no concurrent modification exception occurs.

Void add (E e) inserts the specified element into the List (optional ).
Void remove () removes the last element returned by next or previous from the List (optional ).

1 public static void main (String [] args) {2 ArrayList <String> list = new ArrayList <String> (); 3 4 list. add (null); 5 list. add ("abc1"); 6 list. add ("abc2"); 7 list. add ("abc3"); 8 list. add ("abc4"); 9 10/* 11 * use the Iterator to traverse the set 12 */13 // get the Iterator 14 Iterator <String> it = list. iterator (); 15 // use the while traversal set 16 while (it. hasNext () {17 String s = it. next (); 18 19/* 20 * determine whether there is a "abc3" element 21 * in the set. If there is one, add an element "itcast" 22 * programming skills: when using equals, you need to write the known variables in the front and the unknown ones in the back to prevent null pointer exceptions 23 */24 // if (s. equals ("abc3") {25 if ("abc3 ". equals (s) {26 // 1. iteration is iteration. do not modify the set. 27 // list. add ("itcast"); 28} 29 30 System. out. println (s); 31} 32 33 System. out. println ("------------------"); 34 35/* 36*2. use the add/remove Method in the ListIterator sub-interface of the Iterator to add/remove elements to/from the set by the Iterator. 37 */38 ListIterator <String> listIt = list. listIterator (); 39 while (listIt. hasNext () {40 String s = listIt. next (); 41 if ("abc3 ". equals (s) {42 listIt. add ("itcast"); 43} 44 System. out. println (s); 45} 46 System. out. println (list); 47}

Enhanced
It is an iterator internally, which simplifies iteration code and makes traversal easier.

The Collection interface inherits Iterable, so all the implementation classes of the Collection interface can be enhanced

Note: The enhancement for is after JDK1.5.

Format:
For (data type (Set/array data type) variable name: Set Name/array name ){
Syso (variable name );
}

Generics in Java
Is the data type, which is determined when the object is created

The generic type in Java is a pseudo-generic type: It is found at compilation (in code. java) and does not exist at runtime (. class ).
Random Number: pseudo-random number

Benefits of generics:
1. To avoid strong conversion, you can directly use the element-specific method.
2. Exception during runtime and exception during compilation (compilation failed)

Define classes containing generics
Imitating the ArrayList set
Public class ArrayList <E> {}
E: an unknown data type, which may be Integer, String, or Person.
Determine the data type when creating a class Object

Definition Format:
Modifier class name <E> {

}

 1 public class GenericClass<E> { 2     private E name; 3  4     public E getName() { 5         return name; 6     } 7  8     public void setName(E name) { 9         this.name = name;10     }11     12     public void method(E e){13         System.out.println(e);14     }

Define interfaces with generics
Format:
Modifier interface name <generic> {
Abstract method (parameter <generic type> );
}

1  public interface GenericInterface<E> {2     public abstract void method(E e);3 }
1/* 2*1. define the interface implementation class, no matter how generic or interface generic is written, how can I write 3 * public class ArrayList <E> implements List <E >{} 4 * determine the generic data type when creating an implementation class Object? 5 */6 class GenericInterfaceImpl1 <E> implements GenericInterface <E> {7 8 @ Override 9 public void method (E e) {10 System. out. println (e); 11} 12}

Methods With generics
It is not a generic type defined on the class, it is a generic type defined by the method itself
Definition Format: You must define a wildcard between the modifier and the return value type before using it.
Modifier <generic> return value type method name (parameter <generic> ){
}
Method generics determine the data type when calling the method, what type of data is passed, and what type is generic (it has nothing to do with generics on the class)

1 public class GenericMethod <E> {2 3/* 4 * defines a method, using the generic 5 */6 public void method (E e) on the class {7 System. out. println (e); 8} 9 10/* 11 * defines a method containing generics 12 */13 public <T> void function (T t) {14 System. out. println (t); 15}

Wildcard :?, Represents any data type

Upper Limit :? Extends E-generation table only needs to be a subclass of the E type.
Minimum Limit :? As long as the super E table is an E-type parent class

Construction Method of ArrayList set
ArrayList (Collection <? Extends E> c)
A parameter is a set. The data type of a set is required. It can only be a subclass of the ArrayList generic type or itself.

ArrayList (Collection <? Extends E> c)
A parameter is a set. The data type of a set is required. It can only be a subclass of the ArrayList generic type or itself.

1/* 2 * landlords case: 3*1. prepare the Card 4*2. shuffling 5*3. licensing 6*4. card 7 */8 public class DouDiZhu {9 public static void main (String [] args) {10 // 1. prepare the card 11 // create a collection of 54 cards for storage 12 ArrayList <String> poker = new ArrayList <String> (); 13 // store the King of Kings 14 poker. add (""); 15 poker. add ("Tom"); 16 // store 52 cards 17 // create an array of serial numbers 18 String [] numbers = {"2", "A", "K ", "Q", "J", "10", "9", "8", "7", "6", "5", "4 ", "3"}; 19 // create a color array 20 String [] colors = {"? ","? ","? ","? "}; 21 // nested traversal of two arrays 22 for (String number: numbers) {23 for (String color: colors) {24 // System. out. println (color + number); 25 // Add the combination card to 26 poker in the set. add (color + number); 27} 28} 29 // System. out. println (poker); 30 31/* 32*2. shuffling 33 * use METHOD 34 * static void shuffle (List <?> List) 35 */36 Collections. shuffle (poker); 37 // System. out. println (poker); 38 39/* 40*3. licensing 41 * create 4 sets 42 * traverse poker set 43 * use poker set index % 3 licensing 44 */45 ArrayList <String> player01 = new ArrayList <String> (); 46 ArrayList <String> player02 = new ArrayList <String> (); 47 ArrayList <String> player03 = new ArrayList <String> (); 48 ArrayList <String> diPai = new ArrayList <String> (); 49 // traverse poker set 50 for (int I = 0; I <poker. size (); I ++) {51 // obtain the card 52 String s = poker. get (I); 53 // first determine whether the index is the base card index 51 52 5354 if (I> = 51) {55 // issue 56 diPai to the base card. add (s); 57} else if (I % 3 = 0) {58 // issue Player 1 59 player01.add (s ); 60} else if (I % 3 = 1) {61 // issue Player 1 62 player02.add (s); 63} else if (I % 3 = 2) {64 // authorize Player 1 65 player03.add (s); 66} 67} 68 // 4. card 69 System. out. println ("Andy Lau:" + player01); 70 System. out. println ("Zhou runfa:" + player02); 71 System. out. println ("Stephen CHOW:" + player03); 72 System. out. println ("card:" + diPai); 73} 74}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.