The general method does not work

I try to use this method, but I get an error in Eclipse saying that 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; } 
+4
source share
3 answers

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

Here is an example of a 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 
+1
source

It works with all classes. It does not work with primitives ( int , long , etc.)

Therefore, instead of using primitive arrays, use 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.

+1
source

You can use primitive types if there is no erasure for primitive types. those. int.class is completely impossible, but Integer.class works. Wherever generics are, primitive types are non-go.

0
source

Source: https://habr.com/ru/post/1302512/


All Articles