search
HomeJavajavaTutorialIterator, enhanced for, generic usage collection

Iterator, enhanced for, generic usage collection

Jun 26, 2017 am 11:32 AM
EnhanceGenericsIterategather

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 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     }</string></string></string></string></string></string>

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     }</string></string></string></string>

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     }</e>

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 }</e>
 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 }</e></e></e></e>

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     }</t></e>

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

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

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

ArrayList(Collection extends E> 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 =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 }</string></string></string></string></string></string></string></string></string></string>

 

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment