Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-dimensional generic array initialization

Tags:

java

I tried creating a two-dimensional generic array in java. I get no compile errors, but I get an exception when running the code:

Exception in thread "main" java.lang.ClassCastException: Cannot cast [[[Ljava.lang.String; to [[Ljava.lang.String;
at java.lang.Class.cast(Unknown Source)
at Tabela.<init>(Tabela.java:8)
at TabelaTest.main(TabelaTest.java:4)

Here is the code:

import java.lang.reflect.Array;

public class Tabela<T> {

    private T[][] data;

    public Tabela(Class<T[][]> c,int sizeX, int sizeY) {
        this.data = c.cast(Array.newInstance(c.getComponentType(), sizeX, sizeY));
    }

    public void setInfoAt(T info, int x, int y) {
        this.data[x][y] = info;
    }
    public T getObjectAt(int x, int y) {
        return this.data[x][y];
    }
}

public class TabelaTest {

    public static void main(String args[]) {
        Tabela<String> tabela = new Tabela<String>(String[][].class, 2, 2);

        tabela.setInfoAt("a", 0, 0);
        tabela.setInfoAt("b", 0, 1);
        tabela.setInfoAt("c", 1, 0);
        tabela.setInfoAt("d", 1, 1);

        System.out.println(tabela.getObjectAt(1, 0));
    }
}

It looks like I can't use this method for two dimensional arrays.

EDIT:

Using the method from unholysampler it works now. The constructor was changed to:

public Tabela(Class<T> c,int sizeX, int sizeY) {
    this.data = (T[][])Array.newInstance(c, sizeX, sizeY);
}

The thing is that eclipse keeps warning me about this cast (T[][]). I can supress it, but is it ok to ignore?

like image 340
lhahn Avatar asked Jan 09 '23 18:01

lhahn


1 Answers

If you look at the error message, you will see that the number of square brackets differ.

Cannot cast [[[Ljava.lang.String; to [[Ljava.lang.String;
            ---                      --

You are ending up with the extra array level because of how you are calling Array.newInstance(). If you wanted to just create a String array, you would use:

String[] arr = (String[])Array.newInstance(String.class, 5);

Notice that you pass in the base class type and the method "adds" a layer of brackets. Your call is saying that you want an array that contains instances of 2D arrays of String. Instead, you want to just pass in the base class normally, then specify the dimensions.

Array.newInstance(String.class, sizeX, sizeY);
like image 159
unholysampler Avatar answered Jan 18 '23 00:01

unholysampler