簡體   English   中英

迭代n維數組

[英]Iterate over n-dimensional arrays

如何迭代n維數組( n未知)?

我找到了C ++的結果,其中一個只是運行數組的內存區域,但我不知道我是否可以在JAVA中執行此操作。

我在其他地方找到了這個。 這是一個相當不錯的遞歸解決方案:

 interface Callback {
       void visit(int[] p); // n-dimensional point
    }

void visit(int[] bounds, int currentDimension, int[] p, Callback c) {
   for (int i = 0; i < bounds[currentDimension]; i++) {
        p[currentDimension] = i;
        if (currentDimension == p.length - 1) c.visit(p);
        else visit(bounds, currentDimension + 1, p, c);
   }
}

visit(new int[] {10, 10, 10}, 0, new int[3], new Callback() {
   public void visit(int[] p) {
        System.out.println(Arrays.toString(p));
   }
});

這可以滿足您的需求:

public interface ElementProcessor {    
    void process(Object e);    
}

public static void iterate(Object o, ElementProcessor p) {
    int n = Array.getLength(o);
    for (int i = 0; i < n; i++) {
        Object e = Array.get(o, i);
        if (e != null && e.getClass().isArray()) {
            iterate(e, p);
        } else {
            p.process(e);
        }
    }
}

然后,在打電話時:

// the process method will be called on each element of the n-dimensional
ElementProcessor p = new ElementProcessor() {
    @Override
    public void process(Object e) {
        // simply log for example
        System.out.println(e);
    }
};

int[] a1 = new int[] { 1, 2 };
int[][] a2 = new int[][] { new int[] { 3, 4 }, new int[] { 5, 6 } };

iterate(a1, p);
iterate(a2, p);

這打印:

1
2
3
4
5
6

在C / C ++中,多維數組( int[][] )在內存中以平面方式表示,索引操作符被轉換為指針算術。 這就是為什么用這些語言做到這一點簡單易行的原因。

然而,這不是Java的情況,多維數組是數組的數組。 在嚴格檢查類型時,數組數組中的索引會產生數組類型,而不是內部數組包含的類型。

所以回答這個問題: 不,你不能像在C / C ++中那樣在Java中做到這一點

為此,請參閱其他答案.. :-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM