是否可以在 Java 中动态构建多维数组? [英] Is it possible to dynamically build a multi-dimensional array in Java?

查看:64
本文介绍了是否可以在 Java 中动态构建多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有 Java 代码:

Suppose we have the Java code:

Object arr = Array.newInstance(Array.class, 5);

那会跑吗?进一步说明,如果我们尝试这样的事情会怎样:

Would that run? As a further note, what if we were to try something like this:

Object arr1 = Array.newInstance(Array.class, 2);
Object arr2 = Array.newInstance(String.class, 4);
Object arr3 = Array.newInstance(String.class, 4);
Array.set(arr1, 0, arr2);
Array.set(arr1, 1, arr3);

那么 arr1 将是一个等价于的二维数组:

Would arr1 then be a 2D array equivalent to:

String[2][4] arr1;

这个怎么样:如果我们直到运行时才知道这个数组的维度怎么办?

How about this: what if we don't know the dimensions of this array until runtime?

如果这有帮助(我相信它会......)我们正在尝试从表单的字符串中解析未知维度的数组

if this helps (I'm sure it would...) we're trying to parse an array of unknown dimensions from a String of the form

[value1, value2, ...]

[ [value11, value12, ...] [value21, value22, ...] ...]

等等

Edit2:如果像我这样愚蠢的人尝试这个垃圾,这里有一个至少可以编译和运行的版本.逻辑是否合理完全是另一个问题...

In case someone as stupid as I am tries this junk, here's a version that at least compiles and runs. Whether or not the logic is sound is another question entirely...

Object arr1 = Array.newInstance(Object.class, x);
Object arr11 = Array.newInstance(Object.class, y);
Object arr12 = Array.newInstance(Object.class, y);
...
Object arr1x = Array.newInstance(Object.class, y);
Array.set(arr1, 0, arr11);
Array.set(arr1, 1, arr12);
...
Array.set(arr1, x-1, arr1x);

等等.它必须是一个巨大的嵌套对象数组

And so on. It just has to be a giant nested array of Objects

推荐答案

在java中其实是可以做到的.(我必须说,我有点惊讶.)

It is actually possible to do in java. (I'm a bit surprised I must say.)

免责声明;除了作为这个问题的答案之外,我从不想在其他任何地方看到这段代码.我强烈建议您使用 Lists.

Disclaimer; I never ever want to see this code anywhere else than as an answer to this question. I strongly encourage you to use Lists.

import java.lang.reflect.Array;
import java.util.*;

public class Test {

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

    public static void setValue(Object array, String value, int... indecies) {
        if (indecies.length == 1)
            ((String[]) array)[indecies[0]] = value;
        else
            setValue(Array.get(array, indecies[0]), value, tail(indecies));
    }

    public static void fillWithSomeValues(Object array, String v, int... sizes) {
        for (int i = 0; i < sizes[0]; i++)
            if (sizes.length == 1)
                ((String[]) array)[i] = v + i;
            else
                fillWithSomeValues(Array.get(array, i), v + i, tail(sizes));
    }

    public static void main(String[] args) {

        // Randomly choose number of dimensions (1, 2 or 3) at runtime.
        Random r = new Random();
        int dims = 1 + r.nextInt(3);

        // Randomly choose array lengths (1, 2 or 3) at runtime.
        int[] sizes = new int[dims];
        for (int i = 0; i < sizes.length; i++)
            sizes[i] = 1 + r.nextInt(3);

        // Create array
        System.out.println("Creating array with dimensions / sizes: " +
                Arrays.toString(sizes).replaceAll(", ", "]["));
        Object multiDimArray = Array.newInstance(String.class, sizes);

        // Fill with some 
        fillWithSomeValues(multiDimArray, "pos ", sizes);

        System.out.println(Arrays.deepToString((Object[]) multiDimArray));


    }
}

示例输出:

Creating array with dimensions / sizes: [2][3][2]
[[[pos 000, pos 001], [pos 010, pos 011], [pos 020, pos 021]],
 [[pos 100, pos 101], [pos 110, pos 111], [pos 120, pos 121]]]

这篇关于是否可以在 Java 中动态构建多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆