快速转换,从一维数组两个Java中维 [英] Fast conversion from one-dimensional array to two dimensional in Java

查看:116
本文介绍了快速转换,从一维数组两个Java中维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换很长的[]在Java长[] []尽快。长[]可能不完全对应于长[]和在这种情况下我空行追加到长[]。

I need to convert a long[] to long[][] as quickly as possible in Java. The long[] might not fully correspond to the long[] and in that case I append empty rows to the long[].

目前的code是这样的:

The current code looks like this:

private long[][] convertOneDimensionalToTwoDimensional(int numberOfRows, int rowSize, long[] srcMatrix) {
    int srcMatrixLength = srcMatrix.length;
    int srcPosition = 0;

    long[][] returnMatrix = new long[numberOfRows][];
    for (int i = 0; i < numberOfRows; i++) {
        long[] row = new long[rowSize];
        int nextSrcPosition = srcPosition + rowSize;
        if (srcMatrixLength >= nextSrcPosition) {
            // Copy the data from the file if it has been written before. Otherwise we just keep row empty.
            System.arraycopy(srcMatrix, srcPosition, row, 0, rowSize);
        }
        returnMatrix[i] = row;
        srcPosition = nextSrcPosition;
    }
    return returnMatrix;
}

如何使这种更有效的任何想法?举例来说,有没有什么办法来避免内存复制?

Any ideas on how to make this more efficient? For instance, is there any way to avoid the memory copy?

推荐答案

我想你已经因为你使用的是实现了最快的解决方案 System.arraycopy()。这是最快的解决方案,直到你使用数组。

I think that you have implemented the fastest solution since you are using System.arraycopy(). This is the fastest solution until you are using arrays.

不过,如果性能是一个的真正的问题,在这里,你可以从阵列切换到集合或列表,你可以做的更好实现。您可以实现自己的集合,它使用一维数组,表现为2维的集合。

But if performance is a real issue here and you can switch from arrays to collections or lists you can do better implementation. You can implement your own collection that uses one dimensional array and behaves as 2 dimensional collection.

这篇关于快速转换,从一维数组两个Java中维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆