实现可迭代接口
我刚刚在旧试卷中发现了这个考试问题,并正在为即将到来的考试做好准备。我无法弄清楚:
下面描述了一个实现 Iterable 接口的人为部分类。该类的唯一目的是提供一种方法来迭代属性 things。
我们需要在该类中填写两件事来完成它。 我猜这门课
private class PartialIterableClass /*FILL IN */ {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
/*FILL IN 2*/
}
应该类似于:
private class PartialIterableClass implements Iterable<PrivateIterableClass> {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
public Iterator<PartialIterableClass> iterator( ){
return new Iterator<PartialIterableClass>( ) {
}
}
}
我不太确定如何充实这个问题的答案,有人可以帮忙吗?
I just found this exam question in an old exam paper and am readying myself for an upcoming exam. I cannot figure it out :
The following depicts a contrived partial class which implements the Iterable interface. The only purpose of this class is to provide a method to iterate over the attribute things.
There are two things we need to fill in in the class to finish it. Here is the class
private class PartialIterableClass /*FILL IN */ {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
/*FILL IN 2*/
}
I am guessing it should be something similar to :
private class PartialIterableClass implements Iterable<PrivateIterableClass> {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
public Iterator<PartialIterableClass> iterator( ){
return new Iterator<PartialIterableClass>( ) {
}
}
}
I'm not really sure how to flesh out an answer to this question though, can anybody help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
Iterator
必须实现Iterator
接口中的所有方法,以便封装迭代逻辑。在您的情况下,它将必须保存数组中的当前迭代索引。您可以查看
来自 commons-collections 的 ArrayIterator
Your
Iterator
must implement all the methods from theIterator
interface in order to encapsulate the iteration logic.In your case, it will have to hold the current iteration index in the array. You can look at
ArrayIterator
from commons-collections最简单的方法可能是创建一个新的 ArrayList(),其中填充了
things
中的值,并返回对其的调用结果>.iterator()
方法。这当然是我在时间有限的情况下(例如考试)会做的事情,而且很可能在现实世界中我会做的事情,只是为了让事情变得简单。您可以编写自己的 ArrayIterator 类,或者使用您可以在网络上找到的各种库中的一个类,但这似乎会增加不必要的复杂性。
The easiest thing to do would probably be to create a
new ArrayList<String>()
populated with the values inthings
, and return the result of a call to its.iterator()
method. That's certainly what I'd do in a situation with limited time (like an exam), and quite likely what I'd do in a real-world scenario, just to keep things simple.You could write your own
ArrayIterator
class, or use one from various libraries you can find around the web, but it seems like that would add unnecessary complexity.您可以使用 ArrayIterator,或构建您自己的迭代器,如下所示:
You can use
ArrayIterator
, or build your own iterator like this: