Reputation: 155
I'm new in java programming and of an Objects matrix that I can cast easily using two for loops in this way
String[][] data = new String[objData.length][objData[0].length];
for (int nRow = 0; nRow < objData.length; nRow++){
for (int nCol = 0; nCol < objData[0].length; nCol++){
data[nRow][nCol] = (String) objData[nRow][nCol];
}
}
I was wondering if it can be programmed in a better way. I was trying to use Arrays.copyOf or something similar, like this
String[][] data = Arrays.copyOf(objData, objData.length*objData[0].length, String[][].class);
but this is giving me an exception...
at java.util.Arrays.copyOf(Unknown Source)
Thanks in advance!
Upvotes: 0
Views: 1154
Reputation: 114777
If source and target array are of different types, then your code is the right approach: create a new target array, then copy&convert all items from the source array to the target cells.
Other methods (like Array.copyof()
) will do the same, maybe slightly faster, because they may have their routines implemented in native code. But the complexity is O(m*n)
in all cases.
To tidy up the code: move the algorithm in a static helper method in some utility class, like
public static String[][] convertToStringMatrix(Object[][] source) { ... }
Upvotes: 0
Reputation: 115338
The only way to copy arrays that is more efficient than for() loop coding is System.arraycopy(). It works using low-level call - something like memcopy in C. It should work for you if you pass correct arguments.
But, I'd like to recommend you something. Do not create so hard-to-understand structures. I have probably created 2 dimensional array in java 2 or 3 times during last 12 years. If your data is complex create class that holds this data and then create collection or array that holds elements of this class.
Upvotes: 1