tags:

views:

103

answers:

3

I'm trying to use this method but I get an error in Eclipse saying the type argument is incorrect and it tells me to change the method signature. Any reason why?

/**Creates an independent copy(clone) of the T array.
 * @param array The 2D array to be cloned.
 * @return An independent 'deep' structure clone of the array.
 */
public static <T> T[][] clone2DArray(T[][] array) {
    int rows=array.length ;

    //clone the 'shallow' structure of array
    T[][] newArray = array.clone();

    //clone the 'deep' structure of array
    for(int row=0;row<rows;row++){
        newArray[row]=array[row].clone();
    }

    return newArray;
}
+1  A: 

It works with all classes. It doesn't work with primitives (int, long, etc.)

So instead of using primitive arrays use the wrapper classes: use Integer[][] instead of int[][].

You can use commons-lang ArrayUtils.toPrimitive(..) and ArrayUtils.toObject(..) to convert arrays between primitives and their wrappers.

Bozho
This is because a generic type must extend `Object` (http://stackoverflow.com/questions/112320/is-static-metaprogramming-possible-in-java)
Mark E
+1  A: 

The copy2DArray method you posted appears to work as advertised. Perhaps you are calling the method incorrectly? Also make sure you are not using primitive types instead of objects in the array you are copying. In other words, use Integer instead of int.

Here is an example of the working method:

public class Main {

    // ...
    // Your copy2DArray method goes here
    // ...

    public static void main(String[] args) {
        // The array to copy
        Integer array[][] = {
            {0, 1, 2},
            {3, 4, 5},
            {6, 7, 8}
        };

        // Create a copy of the array
        Integer copy[][] = clone2DArray(array);

        // Print the copy of the array
        for (int i = 0; i < copy.length; i++) {
            for (int j = 0; j < copy[i].length; j++) {
                System.out.print(copy[i][j] + " ");
            }

            System.out.println();
        }
    }
}

This code will print:

0 1 2 
3 4 5 
6 7 8 
William Brendel
Hi, I am not using Primative types and it is still not working. I am using an Interface I have made called Gridable
jax
A: 

You may be using primitive types, when there's no erasure for primitive types. i.e., int.class is completely impossible, but Integer.class works. Wherever generics are involved, primitive types are a no-go.

Chris Dennett