我是Java的初学者,需要编写一个next()
方法,该方法将返回2D数组中当前值。
例如,我们可能有以下内容:
int[][] values = {{1, 2}, {3, 4}, {5, 6}};
当我们第一次使用 next()
函数时,它返回 1
,第二次使用时返回 2
,第三次返回 3
,以此类推。
我的解决方案是将该 2D 数组转换为 1D 数组:
public int[] convert(int[][] array) {
// At first, count number of all cells to set length for new 1D array.
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
count++;
}
}
// Now we have length. Creating new array and filling it with data from all arrays.
int[] result = new int[count];
int index = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
result[index] = array[i][j];
index++;
}
}
return result;
}
然后只需从新的一维数组中获取一个值(position
是类字段 = 0
,values
也是类字段 - int [][] values
):
public int next() {
int[] tmp = convert(values);
int result = tmp[position];
position++;
return result;
}
但很明显,这种解决方案不是最好的。有没有一种方法可以在不转换数组的情况下完成这个操作?类似于迭代器的
next()
和hasNext()
方法吗?更新。我写了一些糟糕的代码来说明我想做什么:
public class ArrayConverter {
private final int[][] values;
private int upper = 0;
private int lower = -1;
public ArrayConverter(int[][] values) {
this.values = values;
}
public int next() {
lower++;
int result = 0;
try {
result = values[upper][lower];
} catch (ArrayIndexOutOfBoundsException a) {
lower = 0;
upper++;
try {
result = values[upper][lower];
} catch (ArrayIndexOutOfBoundsException r) {
upper = 0;
lower = -1;
System.out.print("Reached the end of data. Indexes will be zeroed.");
}
}
return result;
}
}
那段代码之所以糟糕,是因为使用了try/catch语句块,我更倾向于避免使用它。有什么好的方法吗?