将数组分成更小的部分

mal*_*lak 11 java arrays

我想将一个大字节数组分成更小的块(比如说64字节).请帮我解决一下这个.

Dam*_*ash 14

您可以使用方法Arrays.copyOfRange(original,from,to)

 public static byte[][] divideArray(byte[] source, int chunksize) {


        byte[][] ret = new byte[(int)Math.ceil(source.length / (double)chunksize)][chunksize];

        int start = 0;

        for(int i = 0; i < ret.length; i++) {
            ret[i] = Arrays.copyOfRange(source,start, start + chunksize);
            start += chunksize ;
        }

        return ret;
    }
Run Code Online (Sandbox Code Playgroud)

或者您可以使用Max建议的System.arraycopy

public static byte[][] divideArray(byte[] source, int chunksize) {


        byte[][] ret = new byte[(int)Math.ceil(source.length / (double)chunksize)][chunksize];

        int start = 0;

        for(int i = 0; i < ret.length; i++) {
            if(start + chunksize > source.length) {
                System.arraycopy(source, start, ret[i], 0, source.length - start);
            } else {
                System.arraycopy(source, start, ret[i], 0, chunksize);
            }
            start += chunksize ;
        }


        return ret;
    }
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果 source.length 不是块大小的偶数倍,那么第二个块似乎会分配“太大”的最后一个块... (2认同)

Mir*_*ert 12

Damian Vash的第一个方法(使用Arrays.copyOfRange()的方法)如果输入不是chunksize的多个,则将零添加到最后一个块的末尾.

你可能想要使用它:

public static List<byte[]> divideArray(byte[] source, int chunksize) {

    List<byte[]> result = new ArrayList<byte[]>();
    int start = 0;
    while (start < source.length) {
        int end = Math.min(source.length, start + chunksize);
        result.add(Arrays.copyOfRange(source, start, end));
        start += chunksize;
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

如果它有用,使用ArrayList的相同的东西:

  public static List<List<String>> divideList(List<String> source, int chunksize) {
    List<List<String>> result = new ArrayList<List<String>>();
    int start = 0;
    while (start < source.size()) {
      int end = Math.min(source.size(), start + chunksize);
      result.add(source.subList(start, end));
      start += chunksize;
    }
    return result;
  }
Run Code Online (Sandbox Code Playgroud)