Home  >  Article  >  Java  >  Iterator, enhanced for, generic usage collection

Iterator, enhanced for, generic usage collection

巴扎黑
巴扎黑Original
2017-06-26 11:32:511356browse

java.util.Collection interface
is the top-level interface of the collection, which defines the common methods of the collection
The interface cannot directly create objects, and uses polymorphism to create objects
Collection< Data type (generic)> coll = new ArrayList();

Iterator
The way to store data in the collection The (data type) is different, and the way to remove elements from the collection is also different. Java provides us with a common way to remove elements, called iterator
. The interface describing the iterator: java.util.Iterator

Abstract method in interface:
boolean hasNext() Returns true if there are still elements that can be iterated. Determine whether there are any elements in the collection, return true if there are any, and false if not
E next() Returns the next element of the iteration. Take out the next element in the collection

The iterator is an interface, you need to find the implementation class of the iterator. The implementation class of the iterator is the internal class of each collection
There is a method in the Collection interface: The iterator method returns an iterator
Iterator iterator() returns an iterator that iterates over the elements of this collection.
The ArrayList collection implements the Collection interface and overrides the iterator method. The return value of the method is the implementation class object of the iterator.

Note: We only need to know that the iterator method returns the implementation class of the iterator. No need to pay attention to which implementation class object is returned. This method of transformation is called interface-oriented programming

Steps to use iterators:
1. Create a collection object and go to Add elements to the collection
2. Use the iterator method in the collection to obtain the implementation class object of the iterator, and use the Iterator interface to receive (polymorphic)
3. Use the hasNext and next methods in the iterator to iterate and take out the collection Elements in

 1 public static void main(String[] args) { 2         //1.创建集合对象,往集合中添加元素 3         //Collection<String> coll = new ArrayList<String>(); 4         Collection<String> coll = new HashSet<String>(); 5         coll.add("姚明"); 6         coll.add("乔丹"); 7         coll.add("詹姆斯"); 8         coll.add("科比"); 9         coll.add("艾弗森");10         //2.使用集合中的方法iterator获取迭代器的实现类对象,使用Iterator接口接收(多态)11         //集合中的数据类型是什么,迭代器的数据类型就是什么,跟着集合走12         Iterator<String> it = coll.iterator();13         //3.使用iterator中的方法hasNext和next方法进行迭代,取出集合中的元素14         //boolean hasNext() 如果仍有元素可以迭代,则返回 true。15         /*boolean b = it.hasNext();16         System.out.println(b);17         //E(String) next() 返回迭代的下一个元素。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,没有元素了43         s = it.next();//没有元素了,在取就报NoSuchElementException没有元素异常44         System.out.println(s);*/45         46         /*47          * 发现以上迭代的过程是一个重复的过程,可以使用循环优化48          * 我们不知道集合中有多少元素,所以可以使用while循环49          * while循环的结束条件:hasNext();返回false50          */51         while(it.hasNext()){52             String s = it.next();53             System.out.println(s);54         }55         System.out.println("-------------------");56         /*57          * for循环方式迭代器,使用不多58          */59         /*for(Iterator<String> it2 = coll.iterator();it2.hasNext();){60             String s = it2.next();//取出元素,移动指针到下一位61             System.out.println(s);62         }*/63     }

Concurrent modification exception
During the iteration process, if the length of the collection is modified, a concurrent modification exception will occur
During the traversal process, the length of the collection is modified, but the iterator does not know it, and a ConcurrentModificationException will occur

Solution:
1. Iteration is iteration, don’t do it wrong Modify the collection
2. Use the add/remove method in the sub-interface ListIterator of the iterator to let the iterator itself add elements to/remove elements from the collection
In this way, the iterator itself knows the changes in the collection. No concurrent modification exception will occur.

void add(E e) Inserts the specified element into the list (optional operation).
void remove() Removes the last element returned by next or previous from the list (optional operation).

 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          * 使用迭代器遍历集合12          */13         //获取迭代器14         Iterator<String> it = list.iterator();15         //使用while遍历集合16         while(it.hasNext()){17             String s = it.next();18             19             /*20              * 判断集合中有没有"abc3"这个元素21              * 如果有,增加一个元素"itcast"22              * 编程技巧:使用equals判断的时候,要把已知的变量写在前边,未知的写在后边,防止空指针异常23              */24             //if(s.equals("abc3")){25             if("abc3".equals(s)){26                 //1.迭代就是迭代,不要对集合进行修改27                 //list.add("itcast");28             }29             30             System.out.println(s);31         }32         33         System.out.println("------------------");34         35         /*36          * 2.使用迭代器Iterator的子接口ListIterator中的方法add/remove,让迭代器自己增加往集合中增加元素/移除元素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 for
The interior is an iterator, which simplifies the iteration code and makes traversal easier

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

Note: Enhanced for is the

format that appeared after JDK1.5:
for( Data type (data type of collection/array) Variable name: collection name/array name){
 syso(variable name);
}

Generics in Java
It is the data type, which is determined when creating the object.

Generics in Java are pseudo-generics: when compiling (writing code in .java), when running (.class) No
Random numbers: pseudo-random numbers

Benefits of generics:
1. To avoid forced conversion, you can directly use element-specific methods
2. Run Period exception, conversion compile-time exception (compile failure)

Define a class containing generics
Imitate ArrayList collection
public class ArrayList{}
E: is an unknown Data type, may be Integer, may be String, may be Person
Determine the data type when creating a class object

Definition format:
Modifier class class name{

}

 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 an interface containing generics
Format:
Modifier interface interface name{
Abstract method (parameter);
}

1  public interface GenericInterface<E> {2     public abstract void method(E e);3 }
 1 /* 2  * 1.定义接口的实现类,不管泛型,接口泛型是怎么写的,实现类也怎么写 3  *  public class ArrayList<E> implements List<E>{} 4  *  创建实现类对象的时候确定泛型的数据类型 5  */ 6 class GenericInterfaceImpl1<E> implements GenericInterface<E>{ 7  8     @Override 9     public void method(E e) {10         System.out.println(e);11     }12 }

Containing generic methods
It is not a generic defined on the class, but a generic defined by the method itself.
Definition format: A generic must be defined between the modifier and the return value type to use
Modifier Return Value type method name (parameter ){
}
The generic type on the method determines the data type when calling the method, what type of data is passed, and what type the generic is ( It has nothing to do with generics on the class)

 1 public class GenericMethod<E> { 2  3     /* 4      * 定义方法,使用类上的泛型 5      */ 6     public void method(E e){ 7         System.out.println(e); 8     } 9     10     /*11      * 定义一个含有泛型的方法12      */13     public <T> void function(T t){14         System.out.println(t);15     }

泛型的通配符:?,代表任意的数据类型

上限限定:? extends E代表只要是E类型的子类即可
下限限定:? super E代表只要是E类型的父类即可

ArrayList集合的构造方法
ArrayList(Collection c)
参数是一个集合,集合的数据类型有要求,只能是ArrayList泛型的子类或者是本身

ArrayList(Collection c)
参数是一个集合,集合的数据类型有要求,只能是ArrayList泛型的子类或者是本身

 1 /* 2  * 斗地主案例: 3  * 1.准备牌 4  * 2.洗牌 5  * 3.发牌 6  * 4.看牌 7  */ 8 public class DouDiZhu { 9     public static void main(String[] args) {10         //1.准备牌11         //创建存储54张牌的集合12         ArrayList<String> poker = new ArrayList<String>();13         //存储大王小王14         poker.add("大王");15         poker.add("小王");16         //存储52张牌17         //创建序号的数组18         String[] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};19         //创建花色数组20         String[] colors = {"?","?","?","?"};21         //嵌套遍历两个数组22         for (String number : numbers) {23             for (String color : colors) {24                 //System.out.println(color+number);25                 //把组合的牌放入到集合中26                 poker.add(color+number);27             }28         }29         //System.out.println(poker);30         31         /*32          * 2.洗牌33          * 使用Collections中的方法34          * static void shuffle(List<?> list)  
35          */36         Collections.shuffle(poker);37         //System.out.println(poker);38         39         /*40          * 3.发牌41          * 创建4个集合42          * 遍历poker集合43          * 使用poker集合的索引%3发牌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         //遍历poker集合50         for (int i = 0; i < poker.size(); i++) {51             //获取牌52             String s = poker.get(i);53             //先判断索引是否为底牌的索引 51 52 5354             if(i >=51){55                 //给底牌发牌56                 diPai.add(s);57             }else if(i%3==0){58                 //给玩家1发牌59                 player01.add(s);60             }else if(i%3==1){61                 //给玩家1发牌62                 player02.add(s);63             }else if(i%3==2){64                 //给玩家1发牌65                 player03.add(s);66             }67         }68         //4.看牌69         System.out.println("刘德华:"+player01);70         System.out.println("周润发:"+player02);71         System.out.println("周星驰:"+player03);72         System.out.println("底牌:"+diPai);73     }74 }

 

The above is the detailed content of Iterator, enhanced for, generic usage collection. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn