0

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.