Can you create a Java Iterator over a 2d array?
Can you create a single It开发者_运维技巧erator that will step over all spaces in a 2d array?
If you implement the Iterable
interface, you can use a for-each loop
. Related examples may be found here.
Yes, wrap the array in an object and make the object implement the iterator interface. So it can be done. I am not aware of any such iterator that ships with the Jdk.
Yes, it can be done, as @Scorpion says. In fact, the solution is probably pretty simple: no more than 10 lines of executable code ... if I correctly understand the problem.
No, there isn't a convenience method in the JDK to do this. And I'm not aware of one in any of the "commons" libraries. (Reason: this particular problem is too specialized to be useful to more than a handful of programmers.)
This should be a sufficient answer for you to go and implement the solution yourself.
Should I / we provide you a potted solution? IMO, no.
StackOverflow is not a "we write your code for free" service.
If you do it yourself you will learn more: read the excellent "What have you tried?" blog article.
(And even if someone did feel like writing the code for you, you didn't give a clear enough description of the problem to implement ... without making lots of guesses.)
I dont see the need to make a single iterator when invoking the two from the arrays works just fine as per example:
int 2dArray[][];
for(int 1dArray[]: 2dArray){
for(int i: 1dArray){
//do stuff
}
}
import java.util.LinkedList;
import java.util.Queue;
public class TwoDIterator {
int[][] array;
int outerCursor;
int lastArrayLen;
int totalElems;
int tracker = 1;
Queue<Integer> myQueue = new LinkedList<>();
public TwoDIterator(int[][] arr) {
this.array = arr;
this.outerCursor = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
totalElems += 1;
}
}
for (int i = 0; i < array[0].length; i++) {
myQueue.add(array[0][i]);
}
}
public boolean hasNext() {
return array.length > outerCursor && totalElems >= tracker;
}
public Integer next() {
if (myQueue.isEmpty()) {
outerCursor++;
for (int i = 0; i < array[outerCursor].length; i++) {
myQueue.add(array[outerCursor][i]);
}
if (!myQueue.isEmpty()) {
tracker++;
return myQueue.remove();
}
} else {
tracker++;
return myQueue.remove();
}
return -1;
}
public static void main(String[] args) {
int[][] arr = { { 1, 2, 3 }, { 1, 3 }, { 1, 2, 5 } };
TwoDIterator iter = new TwoDIterator(arr);
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
精彩评论