我的問題是這樣的:我有一個迭代器類,它應該遍歷給定的數據結構中的元素,我們可以說,但是我設法完成的是當我傳入數據結構,它將迭代數據結構本身。迭代通過數據結構的元素而不是集合
即。 DynamicIterator it = new DynamicIterator(da);
說da是一個數組輸出將是[1,2,3,4,5,6]而不是1,2,3,4,5,6
我的問題是,更重要的是,理解處理這一問題的普遍接受的做法不僅僅是問題本身。
編輯代碼:
public class X<E>
{
private final E[] rray;
private int currentIndex = 0;
public X(E... a)
{
//if the incoming array is null, don't start
if(a == null)
{
System.out.println("Array is null");
System.exit(1);
}
//set the temp array (rray) to the incoming array (a)
this.rray = a;
}
//hasNext element?
public boolean hasNext()
{
return rray.length > currentIndex;
}
//next element (depends on hasNext())
public E next()
{
if (!hasNext())
{
System.out.println("Element doesn't exist, done");
System.exit(1);
}
return rray[currentIndex++];
}
//return array
public E[] access()
{
return rray;
}
}
你可以使用反射來做到這一點。按照本教程從類中獲取每個字段和值:http://tutorials.jenkov.com/java-reflection/fields.html。 –
感謝您的迴應!我會給它一個鏡頭。 – Hans
這裏的問題是我們不知道任何關於底層數據結構的知識,只能說你可以迭代它。 – Hans