java 迭代器跳出迭代

In this post we are going to discuss about some basics of Java Enumeration and in-depth discussion about Java Iterator. As Java Enumeration interface is deprecated, it is not recommended to use this in our applications.

在本文中,我们将讨论有关Java枚举的一些基础知识,以及有关Java Iterator的深入讨论。 由于不推荐使用Java Enumeration接口,因此不建议在我们的应用程序中使用它。

发布简要目录 (Post Brief Table of Content)

In this post we are going to this discuss the following concepts about Java’s Iterator.

在本文中,我们将讨论有关Java迭代器的以下概念。

  • Java Four CursorsJava四光标
  • Java Enumeration LimitationsJava枚举限制
  • Java IteratorJava迭代器
  • Java Iterator Class DiagramJava Iterator类图
  • Java Iterator MethodsJava迭代器方法
  • Java Iterator Basic ExampleJava Iterator基本示例
  • Develop Custom Class Iterator开发自定义类迭代器
  • How Java Iterator Works Internally?Java Iterator如何在内部工作?
  • Advantages of Java IteratorJava Iterator的优点
  • Limitations of Java IteratorJava Iterator的局限性
  • Similarities between Java Enumeration and IteratorJava枚举和迭代器之间的相似之处
  • Differences between Java Enumeration and IteratorJava枚举和迭代器之间的区别

Java四光标 (Java Four Cursors)

First of all, I would like to define what is a Java Cursor? A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one.

首先,我想定义什么是Java游标? Java游标是一个迭代器,用于迭代,遍历或检索Collection或Stream对象的元素。

Java supports the following four different cursors.

Java支持以下四个不同的游标。

  • Enumeration枚举
  • Iterator迭代器
  • ListIteratorListIterator
  • Spliterator分流器

Each Java cursor have some advantages and drawbacks. We will discuss some basics about Enumeration and full details about Iterator in this posts. We will discuss about ListIterator and Spliterator in my coming posts.

每个Java游标都有一些优点和缺点。 在本文中,我们将讨论有关枚举的一些基础知识和有关Iterator的完整详细信息。 我们将在我的后续文章中讨论ListIterator和Spliterator。

Java枚举限制 (Java Enumeration Limitations)

Java Enumeration is available since Java 1.0 and it has many limitations and not advisable to use in new projects.

Java枚举自Java 1.0开始可用,它具有许多局限性,建议不要在新项目中使用。

  • It is available since Java 1.0 and legacy interface.从Java 1.0和旧版接口开始可用。
  • It is useful only for Collection Legacy classes.它仅对Collection Legacy类有用。
  • Compare to other Cursors, it has very lengthy method names: hasMoreElements() and nextElement().与其他Cursors相比,它具有很长的方法名称:hasMoreElements()和nextElement()。
  • In CRUD Operations, it supports only READ operation. Does not support CREATE, UPDATE and DELETE operations.在CRUD操作中,它仅支持READ操作。 不支持CREATE,UPDATE和DELETE操作。
  • It supports only Forward Direction iteration. That’s why it is also know as Uni-Directional Cursor.它仅支持正向迭代。 这就是为什么它也被称为单向光标。
  • It is not recommended to use it in new code base or projects.不建议在新的代码库或项目中使用它。

NOTE:- What is CRUD operations in Collection API?

注意:-什么是Collection API中的CRUD操作?

  • CREATE: Adding new elements to Collection object.创建:向Collection对象添加新元素。
  • READ: Retrieving elements from Collection object.阅读:从Collection对象中检索元素。
  • UPDATE: Updating or setting existing elements in Collection object.更新:更新或设置Collection对象中的现有元素。
  • DELETE: Removing elements from Collection object.删除:从集合对象中删除元素。

To overcome all these issues, Java come-up with new Cursors: Iterator and ListIterator in Java 1.2. It has introduced a new type of Cursor: Spliterator in Java 1.8.

为了克服所有这些问题,Java提出了新的Cursors:Java 1.2中的Iterator和ListIterator。 它引入了一种新型的Cursor:Java 1.8中的Spliterator。

We will discuss about Iterator with some suitable examples in this post.

在本文中,我们将通过一些合适的示例来讨论Iterator。

Java迭代器 (Java Iterator)

In Java, Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a collection of objects.

在Java中,Iterator是java.util包中Collection框架中可用的接口。 它是用于迭代对象集合的Java游标。

  • It is used to traverse a collection object elements one by one.它用于遍历一个集合对象元素。
  • It is available since Java 1.2 Collection Framework.从Java 1.2 Collection Framework开始可用。
  • It is applicable for all Collection classes. So it is also known as Universal Java Cursor.它适用于所有Collection类。 因此,它也被称为通用Java游标。
  • It supports both READ and REMOVE Operations.它支持读取和删除操作。
  • Compare to Enumeration interface, Iterator method names are simple and easy to use.与Enumeration接口相比,Iterator方法名称简单易用。

Java Iterator类图 (Java Iterator Class Diagram)

As shown in the Class Diagram below, Java Iterator has four methods. We are already familiar with first four methods. Oracle Corp has added fourth method to this interface in Java SE 8 release.

如下面的类图所示,Java Iterator有四个方法。 我们已经熟悉前四种方法。 Oracle Corp在Java SE 8版本中已向该接口添加了第四种方法。

Java迭代器方法 (Java Iterator Methods)

In this section, we will discuss about Java Iterator methods in-brief. We will explore these methods in-depth with some useful examples in the coming section.

在本节中,我们将简要讨论Java Iterator方法。 在下一节中,我们将通过一些有用的示例深入探讨这些方法。

  • boolean hasNext():Returns true if the iteration has more elements.boolean hasNext():如果迭代具有更多元素,则返回true。
  • E next(): Returns the next element in the iteration.E next():返回迭代中的下一个元素。
  • default void remove(): Removes from the underlying collection the last element returned by this iterator.默认void remove():从基础集合中移除此迭代器返回的最后一个元素。
  • default void forEachRemaining(Consumer action): Performs the given action for each remaining element until all elements have been processed or the action throws an exception.默认void forEachRemaining(Consumer action):对每个剩余元素执行给定的操作,直到处理完所有元素或该操作引发异常为止。

Java Iterator基本示例 (Java Iterator Basic Example)

First discuss about how to get an Iterator object from a Collection. Each and every Collection class has the following iterator() method to iterate it’s elements.

首先讨论如何从集合中获取Iterator对象。 每个Collection类都有以下iterator()方法来迭代其元素。

Iterator<E> iterator()

It returns an iterator over the elements available in the given Collection object.

它在给定Collection对象中可用的元素上返回一个迭代器。

Example-1:-

示例1:-

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;public class ExternalIteratorDemo
{public static void main(String[] args) {List<String> names = new LinkedList<>();names.add("Rams");names.add("Posa");names.add("Chinni");// Getting IteratorIterator<String> namesIterator = names.iterator();// Traversing elementswhile(namesIterator.hasNext()){System.out.println(namesIterator.next());          }   }
}

Example-2:-

示例2:-

import java.util.LinkedList;
import java.util.List;public class InternalIteratorDemo
{public static void main(String[] args) {List<String> names = new LinkedList<>();names.add("Rams");names.add("Posa");names.add("Chinni");for(String name: names){System.out.println(name);           }   }
}

If we observe the two above examples, both examples are doing the same thing. In Example-1, we have created Iterator object externally and retrieved List object elements one by one. In Example-2, we have Not created Iterator object externally. We are using Enhanced for loop to retrieve the List object elements one by one.

如果我们观察以上两个示例,则两个示例都在做相同的事情。 在Example-1中,我们在外部创建了Iterator对象,并一个接一个地检索List对象元素。 在示例2中,我们没有在外部创建Iterator对象。 我们正在使用增强的for循环来逐一检索List对象元素。

Enhanced for loop uses Iterator object internally and do the same thing like External Iterator example. So both examples gives the same output as shown below.

增强的for循环在内部使用Iterator对象,并执行与External Iterator示例相同的操作。 因此,两个示例的输出均相同,如下所示。

Output:-

输出:-

Rams
Posa
Chinni

开发自定义类迭代器 (Develop Custom Class Iterator)

In previous section, we have discussed about how Collection API has implemented the iterator() method to iterate it’s elements with or without using Enhanced For Loop.

在上一节中,我们讨论了Collection API如何实现iterator()方法以在使用或不使用Enhanced For Loop的情况下迭代其元素。

In this section, we will discuss about how to provide similar kind of functionality for a User-Defined or Custom classes. We should follow these instructions to provide this functionality:

在本节中,我们将讨论如何为用户定义或自定义类提供类似的功能。 我们应该按照以下说明提供此功能:

  • Define Custom class.定义自定义类。
  • Define Collection class to this Custom class.将此Collection类定义为该Custom类。
  • This Collection class should implement Iterable interface with Custom class as Type parameter.此Collection类应使用Custom类作为Type参数实现Iterable接口。
  • This Collection class should provide implementation of Iterable interface method: iterator().这个Collection类应该提供Iterable接口方法的实现: iterator()

If we implement these instructions to our Custom class, then it’s ready to use Enhanced For Loop or external Iterator object to iterate it’s elements.

如果我们对Custom类实现这些指令,则可以使用Enhanced For Loop或外部Iterator对象来迭代其元素。

Let us develop a simple example to understand these instructions clearly.

让我们开发一个简单的示例来清楚地理解这些说明。

Example:-

例:-

public class Employee {private int empid;private String ename;private String designation;private double salary;public Employee(int empid,String ename,String designation,double salary){this.empid = empid;this.ename = ename;this.designation = designation;this.salary = salary;}public int getEmpid() {return empid;}public String getEname() {return ename;}public String getDesignation() {return designation;}public double getSalary() {return salary;} @Overridepublic String toString(){return empid + "\t" + ename + "\t" + designation + "\t" + salary;    }}
import java.util.*;public class Employees implements Iterable{private List<Employee> emps = null;public Employees(){emps = new ArrayList<&glt;();emps.add(new Employee(1001,"Rams","Lead", 250000L));emps.add(new Employee(1002,"Posa","Dev", 150000L));emps.add(new Employee(1003,"Chinni","QA", 150000L));}@Overridepublic Iterator<Employee> iterator() {return emps.iterator();}}
public class EmployeesTester {public static void main(String[] args) {Employees emps = new Employees();for(Employee emp : emps){System.out.println(emp);}}
}

Output:-

输出:-

1001 Rams    Lead    250000.0
1002    Posa    Dev 150000.0
1003    Chinni  QA  150000.0

Java Iterator如何在内部工作? (How Java Iterator Works Internally?)

In this section, we will try to understand how Java Iterator and it’s methods works internally. Let us take the following LinkedList object to understand this functionality.

在本节中,我们将尝试了解Java Iterator及其方法在内部如何工作。 让我们采用以下LinkedList对象来了解此功能。

List<String> names = new LinkedList<>();
names.add("E-1");
names.add("E-2");
names.add("E-3");
.
.
.
names.add("E-n");

Now create an iterator object on List object as shown below:

现在,在List对象上创建一个迭代器对象,如下所示:

Iterator<String> namesIterator = names.iterator();

Let us assume “namesIterator” iterator looks like below:

让我们假设“ namesIterator”迭代器如下所示:

Here Iterator’s Cursor is pointing to the before first element of the List. Now we run the following code snippet.

这里,迭代器的游标指向列表的第一个元素之前。 现在,我们运行以下代码片段。

namesIterator.hasNext();namesIterator.next();

When we run the above code snippet, Iterator’s Cursor points to the first element in the List as shown in the above diagram. Then run the following code snippet.

当我们运行上面的代码片段时,Iterator的Cursor指向List中的第一个元素,如上图所示。 然后运行以下代码片段。

namesIterator.hasNext();namesIterator.next();

When we run the above code snippet, Iterator’s Cursor points to the second element in the List as shown in the above diagram. Do this process to reach the Iterator’s Cursor to the end element of the List.

当我们运行上面的代码片段时,Iterator的Cursor指向List中的第二个元素,如上图所示。 执行此过程以将Iterator的Cursor到达List的末尾元素。

After reading the final element, if we run the below code snippet, it returns “false” value.

阅读完最后一个元素后,如果我们运行下面的代码片段,它将返回“ false”值。

namesIterator.hasNext();

As Iterator’s Cursor points to the after the final element of the List, hasNext() method returns false value.

当Iterator的Cursor指向List的最后一个元素之后时,hasNext()方法将返回false值。

After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. So it is also know as Uni-Directional Cursor.

观察所有这些图之后,我们可以说Java Iterator仅支持正向迭代,如下图所示。 因此也称为单向游标。

Java Iterator的优点 (Advantages of Java Iterator)

Compare to Enumeration interface, Java Iterator has the following advantages or benefits.

与Enumeration接口相比,Java Iterator具有以下优点或好处。

  • We can use it for any Collection class.我们可以将其用于任何Collection类。
  • It supports both READ and REMOVE operations.它支持读取和删除操作。
  • It is an Universal Cursor for Collection API.它是Collection API的通用游标。
  • Method names are simple and easy to use them.方法名称简单易用。

Java Iterator的局限性 (Limitations of Java Iterator)

However, Java Iterator has the following limitations or drawbacks.

但是,Java Iterator具有以下限制或缺点。

  • In CRUD Operations, it does NOT support CREATE and UPDATE operations.在CRUD操作中,它不支持CREATE和UPDATE操作。
  • It supports only Forward direction iteration that is Uni-Directional Iterator.它仅支持单向迭代器的正向迭代。
  • Compare to Spliterator, it does NOT support iterating elements parallel that means it supports only Sequential iteration.与Spliterator相比,它不支持并行迭代元素,这意味着它仅支持顺序迭代。
  • Compare to Spliterator, it does NOT support better performance to iterate large volume of data.与Spliterator相比,它不支持更好的性能来迭代大量数据。

To overcome these limitations, Java has introduced two more Cursors: ListIterator and Spliterator. We will discuss about these two cursors in my coming posts.

为了克服这些限制,Java又引入了两个游标:ListIterator和Spliterator。 我们将在我的后续文章中讨论这两个游标。

Java枚举和迭代器之间的相似之处 (Similarities between Java Enumeration and Iterator)

In section we will discuss about similarities between two Java Cursors: Java Enumeration and Iterator

在本节中,我们将讨论两个Java游标之间的相似之处:Java枚举和迭代器

  • Both are Java Cursors.两者都是Java游标。
  • Both are used to iterate a Collection object elements one by one.两者都用于一个Collection对象元素一个一个的迭代。
  • Both supports READ or Retrieval operation.两者都支持READ或Retrieval操作。
  • Both are Uni-directional Java Cursors that means supports only Forward Direction Iteration.两者都是单向Java游标,这意味着仅支持正向迭代。

Java枚举和迭代器之间的区别 (Differences between Java Enumeration and Iterator)

The following table describes the differences between Java Enumeration and Iterator:

下表描述了Java枚举和迭代器之间的区别:

Enumeration Iterator
Introduced in Java 1.0 Introduced in Java 1.2
Legacy Interface Not Legacy Interface
It is used to iterate only Legacy Collection classes. We can use it for any Collection class.
It supports only READ operation. It supports both READ and DELETE operations.
It’s not Universal Cursor. Its a Universal Cursor.
Lengthy Method names. Simple and easy to use method names.
枚举 迭代器
在Java 1.0中引入 在Java 1.2中引入
旧版界面 不是旧版界面
它仅用于迭代Legacy Collection类。 我们可以将其用于任何Collection类。
它仅支持READ操作。 它支持READ和DELETE操作。
不是通用游标。 它是一个通用光标。
冗长的方法名称。 简单易用的方法名称。

That’s all of about Iterator in Java. I hope these Java Iterator theory and examples will help you in getting started with Iterator programming.

这就是Java中的Iterator的全部内容。 我希望这些Java Iterator理论和示例将帮助您入门Iterator编程。

Thank you for reading my tutorials. Please drop me a comment if you like my tutorials or have any issues or suggestions or any type errors.

感谢您阅读我的教程。 如果您喜欢我的教程或有任何问题或建议或任何类型错误,请给我评论。

翻译自: https://www.journaldev.com/13460/java-iterator

java 迭代器跳出迭代

java 迭代器跳出迭代_Java迭代器– Java中的迭代器相关推荐

  1. java for循环迭代_JAVA中的for-each循环与迭代

    在学习java中的collection时注意到,collection层次的根接口Collection实现了Iterable接口(位于java.lang包中),实现这个接口允许对象成为 "fo ...

  2. java迭代器退出迭代_使用Java迭代器修改数据时要小心

    java迭代器退出迭代 随着本学期的结束,我想我会分享一个关于如何非常熟悉Java迭代器的小故事. 现实世界语境 就上下文而言,我开设了第二年软件组件课程,这是尝试进入该专业的学生的最后障碍. 当然, ...

  3. java怎么加定时器_JAVA WEB程序中添加定时器

    JAVA WEB程序中添加定时器 //这是我的定时器类,用来定时执行某段任务: package com.my.time; import java.text.ParseException; import ...

  4. 取java.sql.date日期_JAVA 处理时间 - java.sql.Date、java.util.Date与数据库中的Date字段的转换方法[转]...

    1.如何将java.util.Date转化为java.sql.Date? 转化: java.sql.Date sd; java.util.Date ud; //initialize the ud su ...

  5. java字符串去掉中文_Java——去除字符串中的中文

    import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemoveStrChinese { priv ...

  6. java倒计时跳出窗口_java 窗口 倒计时 关闭

    展开全部 package mainWindow; import java.awt.*; import javax.swing.*; import java.util.*; import java.io ...

  7. java文件路径转义_java文件路径中“\”和“/”的区别

    java文件路径中"\"和"/"的区别 发布时间:2020-06-25 17:51:22 来源:亿速云 阅读:189 作者:Leah 本篇文章为大家展示了jav ...

  8. java遍历字符串字符_Java 遍历字符串中所有字符的最快方法

    小编典典 在我的AMDx64 8core和源1.8上,使用'charAt'和字段访问之间没有区别.看来jvm已经过充分优化,可以内联和精简任何'string.charAt(n)'调用. 这完全取决于S ...

  9. java队列 双队列_Java队列– Java队列

    java队列 双队列 Java Queue is an interface available in java.util package and extends java.util.Collectio ...

最新文章

  1. angr学习笔记(1)
  2. HDU 1495 非常可乐
  3. 根据方法名执行方法的例子
  4. 乔恩与加菲猫引发的思考
  5. 统计学中【矩】的概念
  6. Eclipse怎样把文件系统形式的项目作为工程直接导入?
  7. Oracle闪回技术(Flashback)
  8. Docker第一章:安装及初始化配置
  9. 一建已经过去,正是中级通信工程师黄金备考期!
  10. python依赖包安装
  11. uploader.php,使用uploader上传拍摄的图片php后端代码出错~求助~
  12. 公文流转 php,河北金力集团公文流转系统----节选
  13. 时钟屏保fliqlo
  14. electron最小化托盘、禁用右键菜单
  15. Python爬虫学习实战
  16. linux 获取视频截图,linux ffmpeg 视频截图 安装使用
  17. win10电脑显示无法自动修复此计算机,win10正式版提示自动修复无法修复你的电脑解决教程...
  18. 蓝桥杯 - 历届试题 小朋友排队 C语言实现
  19. 智能制造 | 机器视觉系统,直击纺织行业人工质检痛点难点,提升缺陷检出精准度至99.9%
  20. python笔记 基础语法·第10课 【田忌赛马游戏,代码拆分,过程代码】

热门文章

  1. 微服务(SpringCloud、Dubbo、Seata、Sentinel、SpringGateway)
  2. 全球与中国啤酒饮料灌装设备市场深度研究分析报告
  3. fifo页面置换算法java_缓存算法(页面置换算法)-FIFO、LFU、LRU
  4. 给初学者的RxJava2.0教程(七)
  5. 展锐平台如何从modem log 中查看终端支持的GEA算法能力
  6. 微服务系列:服务发现与注册-----Eureka(面试突击!你想了解的Eureka都在这里.持续更新中......)
  7. 用构建者的角度去学习一门技术
  8. 4s,5s,6s,6sp屏幕像素
  9. Wine 6.1 正式版发布带来新变化
  10. dotnet 教你写一个可以搞炸本机所有 WCF 应用的程序方法