在Java中声明一个迭代器 [英] Declaring an iterator in Java

查看:110
本文介绍了在Java中声明一个迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的迭代器感到非常困惑。

I'm very confused about the iterator in Java.

本教程正在阅读中说:

在Java编程语言中,接口是一种类似于类的引用类型,它只能包含常量,方法签名和嵌套类型。没有方法体。接口无法实例化 - 它们只能由类实现或由其他接口扩展。扩展将在本课后面讨论。

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson.

然后我看到了另一个教程:

Then I saw another tutorial with this:

Iterator<String> flavoursIter = aFlavours.iterator();

我知道aFlavours已经继承了返回迭代器接口的迭代器函数。我只是不明白这一行实际发生了什么。
我以为你无法实例化?

I understand that aFlavours has inheritated the iterator functions which returns the iterator interface. I just don't understand what is actually happening in this line. I thought you couldn't instantiated?

也许我没有意义,但请告诉我我们要离开赛道了。

Maybe I'm not making sense, but please tell me we're I'm going off the track.

推荐答案

说它无法实例化,它们的意思是你不能做 Iterator i = new Iterator(); 。由于Iterator是一个接口,它本身没有实现。当你这样做时

By saying it can't be instantiated, what they mean is that you can't do Iterator i = new Iterator();. Since Iterator is an interface, it has no implementation by itself. When you do

Iterator flavoursIter = aFlavours.iterator();

你正在做的是在上调用一个名为iterator的方法aFlavours 返回一个实现Iterator接口的类的实例的对象(你真的不知道它究竟是什么类,你也不应该关心,所有你保证的是它支持所有Iterator接口中定义的方法。

what you're doing is calling a method called "iterator" on the aFlavours object that returns an instance of some class that implements the Iterator interface (you don't really know what exact class it is, nor should you care, all that you're guaranteed is that it supports all the methods defined in the Iterator interface).

这篇关于在Java中声明一个迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆