如何声明用户可以指定维度的数组?

发布于 2024-10-16 14:13:46 字数 203 浏览 2 评论 0原文

我想要一个可以做到这一点的函数/数据结构:

func(int dim){

if(dim == 1)

int[] array;

else if (dim == 2)

int[][] array;

else if (dim == 3)

int[][][] array;

..

..

.

}

有人知道怎么做吗?

I want a function / data structure that can do this:

func(int dim){

if(dim == 1)

int[] array;

else if (dim == 2)

int[][] array;

else if (dim == 3)

int[][][] array;

..

..

.

}

anyone know how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情归归情 2024-10-23 14:13:46

编辑

或者您可以使用 Array.newInstance(int.class, 大小)。其中,sizes 是包含所需大小的 int[]。它会工作得更好,因为您实际上可以将结果转换为 int[][][]...


原始答案

您可以使用 int[]Object[]Object。假设您想要一个矩形多维数组,其大小由列表大小给定,

Object createIntArray(List<Integer> sizes) {
    if(sizes.size() == 1) {
        return new int[sizes.get(0)];
    } else {
        Object[] objArray = new Object[sizes.get(0)];
        for(int i = 0; i < objArray.length; i++) {
           objArray[i] = createIntArray(sizes.subList(1, sizes.size());
        }
        return objArray;
    }
}

您将失去所有静态类型检查,但只要您想要动态维度的数组,这种情况就会发生。

Edit

Or you could use Array.newInstance(int.class, sizes). Where sizes is an int[] containing the desired sizes. It will work better because you could actually cast the result to an int[][][]...


Original Answer

You could use the fact that both int[] and Object[] are Objects. Given that you want a rectangular multidimensional array with sizes given by the list sizes

Object createIntArray(List<Integer> sizes) {
    if(sizes.size() == 1) {
        return new int[sizes.get(0)];
    } else {
        Object[] objArray = new Object[sizes.get(0)];
        for(int i = 0; i < objArray.length; i++) {
           objArray[i] = createIntArray(sizes.subList(1, sizes.size());
        }
        return objArray;
    }
}

You lose all static type checking, but that will happen whenever you want a dynamically dimensioned array.

并安 2024-10-23 14:13:46

如果您的目的是创建一个真正的动态数组,那么您应该查看 JDK 中的 Array 对象。您可以使用它来动态生成任何维度的数组。下面是一个示例:

    public void func(int dim) {
        Object array = Array.newInstance(int.class, new int[dim]);
        // do something with the array        
    }

创建数组对象后,您可以使用 java.lang.reflect.Array 类的方法来访问、添加、删除所创建的多维数组中的元素。还包括确定数组实例长度的实用方法。

您甚至可以使用以下方法检查数组的维度:

public int getDimension(Object array) {
    int dimension = 0;
    Class cls = array.getClass();
    while (cls.isArray()) {
        dimension++;
        cls = cls.getComponentType();
    }
    return dimension;
}

If your purpose is to create a truly dynamic array, then you should look at the Array object in the JDK. You can use that to dynamically generate an array of any dimension. Here is an example:

    public void func(int dim) {
        Object array = Array.newInstance(int.class, new int[dim]);
        // do something with the array        
    }

Once the array Object has been created, you can use the methods of the java.lang.reflect.Array class to access, add, remove elements from the multi-dimension array that was created. In also includes utility methods to determine the length of the array instance.

You can even check the dimension of the array using:

public int getDimension(Object array) {
    int dimension = 0;
    Class cls = array.getClass();
    while (cls.isArray()) {
        dimension++;
        cls = cls.getComponentType();
    }
    return dimension;
}
执手闯天涯 2024-10-23 14:13:46

人们已经发布了很好的解决方案,但我认为如果将动态多维数组包装到一个类中,它可以使用任何数据结构来表示多维数组,这会很酷(也是很好的做法)。我使用哈希表,因此您几乎拥有无限的大小维度。

public class MultiDimArray{
  private int myDim;
  private HashMap myArray;

  public MultiDimArray(int dim){
     //do param error checking 
     myDim = dim;
     myArray= new HashMap();
  }

  public Object get(Integer... indexes){
     if (indexes.length != myDim){throw new InvalidArgumentException();}

     Object obj = myArray;
     for (int i = 0; i < myDim; i++){
       if(obj == null)
         return null;

         HashMap asMap = (HashMap)obj;
         obj = asMap.get(indexes[i]);
     }

     return obj;
  }

  public void set(Object value, Integer... indexes){
    if (indexes.length != myDim){throw new InvalidArgumentException();}
      HashMap cur = myArray;
      for (int i = 0; i < myDim - 1; i++){
        HashMap temp = (HashMap)cur.get(indexes[i]);
        if (temp == null){
          HashMap newDim = new HashMap();
          cur.put(indexes[i], newDim);
          cur = newDim;
        }else{
          cur = temp;
        }
     }
     cur.put(indexes[myDim -1], value);
  }
}

你可以像这样使用这个类:

Object myObj = new Object();
MultiDimArray array = new MultiDimArray(3);
array.put(myObj, 0, 1, 2); 
array.get(0, 1, 2); //returns myObj
array.get(4, 5, 6); //returns null

People have post good solutions already, but I thought it'd be cool (and good practice) if you wrap the dynamic multidimensional array into a class, which can use any data structure to represent the multi-dimensional array. I use hash table so you have virtually unlimited size dimensions.

public class MultiDimArray{
  private int myDim;
  private HashMap myArray;

  public MultiDimArray(int dim){
     //do param error checking 
     myDim = dim;
     myArray= new HashMap();
  }

  public Object get(Integer... indexes){
     if (indexes.length != myDim){throw new InvalidArgumentException();}

     Object obj = myArray;
     for (int i = 0; i < myDim; i++){
       if(obj == null)
         return null;

         HashMap asMap = (HashMap)obj;
         obj = asMap.get(indexes[i]);
     }

     return obj;
  }

  public void set(Object value, Integer... indexes){
    if (indexes.length != myDim){throw new InvalidArgumentException();}
      HashMap cur = myArray;
      for (int i = 0; i < myDim - 1; i++){
        HashMap temp = (HashMap)cur.get(indexes[i]);
        if (temp == null){
          HashMap newDim = new HashMap();
          cur.put(indexes[i], newDim);
          cur = newDim;
        }else{
          cur = temp;
        }
     }
     cur.put(indexes[myDim -1], value);
  }
}

and you can use the class like this:

Object myObj = new Object();
MultiDimArray array = new MultiDimArray(3);
array.put(myObj, 0, 1, 2); 
array.get(0, 1, 2); //returns myObj
array.get(4, 5, 6); //returns null
热血少△年 2024-10-23 14:13:46

像下面这样的类怎么样?

class DynaArray {

private List<List> repository = new ArrayList<List>();

public DynaArray (int dim) {
for (int i = 0; i < dim; i++) {
     repository.add(new ArrayList());
}
}

public List get(int i) {
return repository.get(i);
}

public void resize(int i) {
 // resizing array code
}

}

What about a class like following?

class DynaArray {

private List<List> repository = new ArrayList<List>();

public DynaArray (int dim) {
for (int i = 0; i < dim; i++) {
     repository.add(new ArrayList());
}
}

public List get(int i) {
return repository.get(i);
}

public void resize(int i) {
 // resizing array code
}

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文