Md Monjur Ul Hasan
Md Monjur Ul Hasan

Reputation: 1791

Creating generic Java class having a 2D generic array field

I am preparing a class that can handle a hexgrid. I am trying to create a 2D array field for holding the data of that grids. I have the following code prepared. It shows no compilation error, however, one run time error is there. I am new in java programming and do not know what this mean.

Can anyone help me to fix the error or telling me a better way for this problem?

Hex grid Class (HexGrid.java)

import java.lang.reflect.Array;

public class HexGrid <T>{
    int row,col;
    T[][] grid;

    public HexGrid(T[] data){
        int n = data.length;
        int r = (int) Math.ceil(Math.sqrt(n));
        LoadData(r, r, data);
    }       
    public HexGrid(int r,T[] data){
        this(r,(int)(Math.ceil(data.length/r)),data);
    }
    public HexGrid(int r){
        this(r,r,null);
    }
    public HexGrid(int r, int c){
        this(r,c,null);
    }
    public HexGrid(int r,int c,T[] data) {
        LoadData(r, c, data);           
    }

    @SuppressWarnings("unchecked")
    public void LoadData(int r, int c, T[] data){
        Class<? extends T> cls = (Class<? extends T>) data.getClass();
        row     = r;
        col     = c;
        grid    = (T[][]) Array.newInstance(data.getClass(),r, c+(int) Math.floor(r/2.0));
        if(data!=null)
            AssignValues(data);
    }

    private void AssignValues(T[] data) {
        int dbug=0;
        for(int i=0; i<row; i++)
        {
            for(int j= (int)(Math.ceil(i/2));j<col+(int)(Math.floor(row/2)); j++)
            {
                dbug++;
                if(dbug<data.length)
                     grid[i][j] = data[i];
                else grid[i][j] = null;
            }
        }
        System.out.println(dbug+"");
    }

}

Here is a sample example how I would liked to use it (Test.java)

public class Test {

    public static void main(String[] args) {

        Integer[] data= new Integer[96];

        for(int i=0;i<96;i++)
            data[i] = i+1;

        HexGrid<Integer> objHexGrid = new HexGrid<Integer>(data);


    }

}

And the error I am receiving is the followings:

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
    at hexGrid.HexGrid.AssignValues(HexGrid.java:46)
    at hexGrid.HexGrid.LoadData(HexGrid.java:35)
    at hexGrid.HexGrid.<init>(HexGrid.java:13)
    at hexGrid.Test.main(Test.java:12)

Upvotes: 1

Views: 331

Answers (1)

Tamas Hegedus
Tamas Hegedus

Reputation: 29926

The problem is because you allocate an Integer[][][] array, but use it as a Integer[][].

In the following line data.getClass() returns Integer[], so you allocate a matrix of Integer[]-s instead of Integer-s:

grid = (T[][])Array.newInstance(data.getClass(),r, c+(int) Math.floor(r/2.0));

Change the above line to:

grid = (T[][])Array.newInstance(
    data.getClass().getComponentType(), r, c + r / 2);

Upvotes: 2

Related Questions