简体   繁体   English

Java:元组上的“迭代器”

[英]Java: “iterator” over tuples

I have a class Students that has a member bigTable of type ArrayList<ArrayList<Integer>> . 我有具有成员的类的学生bigTable类型的ArrayList<ArrayList<Integer>> If we imagine it asa matrix, I would like to be able to iterate over a specific column, given as a parameter in some iterator initialization. 如果我们将其想象成一个矩阵,我希望能够在特定的列上进行迭代,该列在某些迭代器初始化中作为参数给出。 Also, I would like the iterator to have 2 methods, getValue and getPosition . 另外,我希望迭代器具有2个方法, getValuegetPosition ie something like: 即类似:

1 2 3 1 2 3
9 8 6 9 8 6
3 4 5 3 4 5

Student student = newStudent()
SomeType(what??) it = student.iterator(1);
it.getValue() // returns 2
it.getPosition() // returns 0
it.next() // moves to next position
it.getValue() // returns 8
it.getPosition() // returns 1
...

This interface is just a suggestion. 该界面只是一个建议。 I was thinking about kinda implementing the iterator pattern in Student by doing an inner class. 我正在考虑通过做一个内部类来在Student中实现迭代器模式。 But is it appropriate to return a reference to the inner class?? 但是返回对内部类的引用是否合适? In fact if I want to pass the iterator as an argument to somebody, what type should I say it is? 实际上,如果我要将迭代器作为参数传递给某人,我应该说它是什么类型? (inner class is not visible)... (内部类不可见)...

Is there a more elegant way of accomplishing this task? 有没有更优雅的方式来完成此任务?

Also, just wondering, if I returned the entire row (an ArrayList, in which case Student could implement the Iterator interface) will it occupy extra memory (I mean will it be copied over or just a reference passed?) 另外,我只是想知道,如果我返回整行(一个ArrayList,在这种情况下,Student可以实现Iterator接口),它将占用额外的内存(我的意思是将其复制过来还是只传递一个引用?)

Returning an instance of an inner class is a common way of supplying an Iterator - see the java.util source code for many examples. 返回内部类的实例是提供Iterator的常用方法-有关许多示例,请参见java.util源代码。

I think deviating from the normal Iterator interface would be unnecessarily confusing, especially if you call the method returning it "iterator". 我认为偏离正常的Iterator接口会造成不必要的混乱,尤其是当您调用返回它的方法“ iterator”时。

If you want the iterator() result to let you get something with getValue() and getPosition() methods, declare an interface with those methods. 如果希望iterator()结果允许您使用getValue()getPosition()方法获得某些东西,请使用这些方法声明一个接口。 I'll call it ElementData - you can think of a more meaningful name for your situation. 我将其称为ElementData您可以为您的情况想到一个更有意义的名称。 Your iterator() method can then return Iterator<ElementData> . 然后,您的iterator()方法可以返回Iterator<ElementData>

Your code would become: 您的代码将变为:

Student student = newStudent()
Iterator<ElementData> it = student.iterator(1);
ElementData element;
element = it.next()
element.getValue() // returns 2
element.getPosition() // returns 0
element = it.next() // moves to next position
element.getValue() // returns 8
element.getPosition() // returns 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM