【问题标题】:How to access multidimensional array programmatically in Java?如何在 Java 中以编程方式访问多维数组?
【发布时间】:2014-08-18 08:31:37
【问题描述】:

假设我们有一个多维数组,并且维数只有在运行时才知道。假设我们有整数个索引。

如何对数组应用索引以访问数组的元素?

更新

假设:

int [] indices = new int { 2, 7, 3, ... , 4}; // indices of some element
int X = indices.length; // number of dimensions
Object array = .... // multidimensional array with number of dimensions X

...

我想从array 获取索引indices 寻址的元素。

更新 2

我基于递归编写了以下代码:

package tests;

import java.util.Arrays;

public class Try_Multidimensional {

    private static int element;

    public static int[] tail(int[] indices) {
        return Arrays.copyOfRange(indices, 1, indices.length);
    }


    public static Object[] createArray(int ... sizes) {

        Object[] ans = new Object[sizes[0]];

        if( sizes.length == 1 ) {
            for(int i=0; i<ans.length; ++i ) {
                ans[i] = element++;
            }
        }

        else {
            for(int i=0; i<ans.length; ++i) {
                ans[i] = createArray(tail(sizes)); 
            }
        }

        return ans;

    }

    public static Object accessElement(Object object, int ... indices) {

        if( object instanceof Object[] ) {

            Object[] array = (Object[]) object;

            return accessElement(array[indices[0]], tail(indices));

        }

        else {
            return object;
        }

    }

    public static void main(String[] args) {

        element = 0;
        Object array = createArray(4, 5, 12, 7);

        System.out.println(accessElement(array, 0, 0, 0, 0));
        System.out.println(accessElement(array, 0, 0, 0, 1));
        System.out.println(accessElement(array, 1, 0, 10, 0));
        try {
            System.out.println(accessElement(array, 0, 5, 0, 1));
        }
        catch(Exception e) {
            System.out.println(e.toString());
        }

    System.out.println(4*5*12*7-1);
    System.out.println(accessElement(array, 3, 4, 11, 6));

    }

}

问题是:

1) 有没有来自 JDK 和/或著名库的可靠现成方法?

2) 我使用的是Object。可以避免吗?我可以创建/访问内置或特定类型的可变维度数组吗?使用Object 的回报有多大?

【问题讨论】:

  • 您能否说得更具体一点,也许提供一个代码片段?
  • 你能举个例子吗。看不懂
  • 我建议你阅读this
  • java中没有多维数组..它是数组的数组..
  • @Anirudha 我建议你也阅读我提供的链接...

标签: java arrays multidimensional-array


【解决方案1】:
int index(Object arrayToIndex, int... indices) {
    for (int i = 0; i < indices.length - 1; i++) {
        arrayToIndex = ((Object[]) arrayToIndex)[indices[i]];
    }
    return ((int[]) arrayToIndex)[indices[indices.length-1]];
}

遍历维度并对每个维度进行索引,一次一个。最后一维的强制转换和特殊情况会很烦人,所以我建议将它包装在某种 n 维数组类中。 (It looks like some options already exist.)

【讨论】:

  • 我认为她想创建一个具有 N 维的数组,其中 N 直到运行时才知道,该语言不支持。
  • @JeffScottBrown:这个问题只涉及访问数组。创建它是另一回事。
  • 我和你一样误解了这个问题。问题包括“对象数组 = .... // 维数为 X 的多维数组”,右侧是无法完成的事情。您不能创建具有动态维数的数组,这就是我认为她所追求的。也许我对她的追求是错误的。
  • 问题已经改变,似乎在问一些不同的问题。我要投降了。 ;) 祝 OP 好运。
  • 你为什么不能重写for (int i = 0; i &lt; indices.length - 1; i++) -> for (int i = 0; i &lt; indices.length; i++),最后只写return arrayToIndex;
【解决方案2】:

您可以发现每个维度的大小作为单独的数组(因为它们就是这样):

public void someMEthod(int[][][] matrix) {
    int d1 = matrix.length;
    int d2 = 0;
    int d3 = 0;
    if(d1 > 0) {
        d2 = matrix[0].length;
        if(d2 > 0) {
            d3 = matrix[0][0].length;
        }
    }
    System.out.println("Dimension 1 is " + d1);
    System.out.println("Dimension 2 is " + d2);
    System.out.println("Dimension 3 is " + d3);
}

希望对你有帮助。

【讨论】:

  • 维度的数量是可变的,而不仅仅是每个维度的大小。
  • 我猜这里的问题是数组的维数未知,所以matrix不能任意声明为int[][][]
  • 原始问题已被编辑,因此我不确定这是否真的回答了该问题。目前写的问题的答案是你不能这样做。声明数组时,必须知道维数。这些维度中的每一个的值都可以是运行时动态的,但不是维度的数量。
  • 您可以通过 ArrayList 的 ArrayList 的 ArrayList 的 ArrayList 来做到这一点,在这种情况下,维数可以是动态的,但是关于数组(不是 ArrayList)的问题是这样的,你不能去做吧。
【解决方案3】:

我发现了一种使用反射的有趣方法。这只是我拼凑的一些代码,但你可以将它包装在一个类中并让它变得漂亮。

// build and fill an array to the given depth
public static Object[] constructArray(Object[] array, int depth) {
    if(depth == 0)
        return null;

    for(int i=0;i<array.length;i++) {
        Array.set(array, i, constructArray(new Object[array.length], depth-1));
    }
    return array;
}

// sets a value in the multi dimensional array using the indicies
public static void setArrayUsingIndecies(Object array, int[] indicies, Object value) {
    if(indicies.length == 0)
        return;

    for(int i=0;i<indicies.length-1;i++) {
        array = Array.get(array, indicies[i]);
    }

    Array.set(array, indicies[indicies.length-1], value);
}

// gets a value in the multi dimmensional array using the indicies
public static Object getArrayUsingIndecies(Object array, int[] indicies) {

    Object value = array;
    for(int i=0;i<indicies.length;i++) {
        value = Array.get(value, indicies[i]);
    }

    return value;
}

这里有一些示例代码

int numberOfDimmensions = 2;

Object array = constructArray(new Object[numberOfDimmensions], numberOfDimmensions);

int [] indices = new int [] { 0, 1 };
setArrayUsingIndecies(array, indices, "Hello");
System.out.println(getArrayUsingIndecies(array, indices)); // Hello
indices = new int [] { 0, 0 };
System.out.println(getArrayUsingIndecies(array, indices)); // null

【讨论】:

    【解决方案4】:

    它比我们想象的更简单吗?这种方法怎么样:

    int [] indices = new int { 2, 7, 3, ... , 4}; // indices of some element
    int X = indices.length; // number of dimensions
    Object array = new Object[X].... // multidimensional array with number of dimensions X
    

    然后:

    Object myObject = array[indices[1]]  // myObject references the 7th element of array
    

    您必须确保您的索引数组不包含大于索引大小的数字 - 1。例如

    indices = new int [5,4,3,2,1] // ok
    indices = new int [6,4,3,2,1] // not ok, because you would access the 6th Element in an arry with length 5
    

    【讨论】:

    • 这不是来自C#吗?
    • 对不起,我不明白你的评论?
    猜你喜欢
    • 2014-07-29
    • 2022-06-10
    • 2013-07-08
    • 1970-01-01
    • 2012-05-31
    • 2014-09-17
    • 1970-01-01
    • 2015-09-03
    • 2020-05-05
    相关资源
    最近更新 更多