java中字符串的对象矩阵到矩阵字符串
我是java编程和对象矩阵的新手,我可以使用两个for循环轻松地以这种方式进行转换,
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];
}
}
我想知道是否可以以更好的方式对其进行编程。我试图使用 Arrays.copyOf 或类似的东西,就像这样
String[][] data = Arrays.copyOf(objData, objData.length*objData[0].length, String[][].class);
,但这给了我一个例外......
在 java.util.Arrays.copyOf(Unknown Source)
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
比 for() 循环编码更有效的复制数组的唯一方法是 System.arraycopy()。它使用低级调用工作——类似于 C 中的 memcopy。如果你传递正确的参数,它应该对你有用。
但是,我想向你推荐一些东西。不要创建如此难以理解的结构。在过去的 12 年里,我可能用 java 创建了 2 维数组 2 或 3 次。如果您的数据很复杂,请创建保存此数据的类,然后创建保存此类元素的集合或数组。
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.
如果源数组和目标数组属于不同类型,那么您的代码是正确的方法:创建一个新的目标数组,然后将所有项目从源数组复制并转换到目标单元格。
其他方法(如 Array.copyof())也会执行相同的操作,可能会稍微快一些,因为它们的例程可能是在本机代码中实现的。但在所有情况下,复杂度都是
O(m*n)
。要整理代码:将算法移至某个实用程序类的静态辅助方法中,例如
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 isO(m*n)
in all cases.To tidy up the code: move the algorithm in a static helper method in some utility class, like