Java 将数组拆分为X长度的片段

Java 将数组拆分为X长度的片段,java,arrays,performance,algorithm,Java,Arrays,Performance,Algorithm,目前我有一个大小为N的数组。我正在尝试从数组中复制每X个字节 例如,如果数组大小为10,而我希望数组大小为3。我会复制前3个元素,然后是下3个元素和最后1个元素 目前我正在使用以下算法: int I = 0; int sub = bytes.length; int counter = 0; for (I = 0; I < bytes.length; ++I) { if (I % 3 == 0 && I != 0) { NewArray[counter]

目前我有一个大小为N的数组。我正在尝试从数组中复制每X个字节

例如,如果数组大小为10,而我希望数组大小为3。我会复制前3个元素,然后是下3个元素和最后1个元素

目前我正在使用以下算法:

int I = 0;
int sub = bytes.length;
int counter = 0;
for (I = 0; I < bytes.length; ++I) {
    if (I % 3 == 0 && I != 0) {
       NewArray[counter] = Arrays.copyOfRange(bytes, I - 3, I));
        sub -= 3;
        ++counter;
    }
}

NewArray[counter] = Arrays.copyOfRange(bytes, I - sub, I)); //Copy remainder.
inti=0;
int sub=bytes.length;
int计数器=0;
对于(I=0;I
有没有一种更有效或更体面的方式来做我想做的事情?这个算法看起来很糟糕=l

有什么想法可以改进它或者至少是一个提示吗?

这个怎么样:

int x = 3;  // chunk size
int len = bytes.length;
int counter = 0;

for (int i = 0; i < len - x + 1; i += x)
    newArray[counter++] = Arrays.copyOfRange(bytes, i, i + x);

if (len % x != 0)
    newArray[counter] = Arrays.copyOfRange(bytes, len - len % x, len);
int x=3;//块大小
int len=bytes.length;
int计数器=0;
对于(int i=0;i
您可以将split与特殊的正则表达式一起使用:

 System.out.println(Arrays.toString(
     "Thisismystringiwanttosplitintogroupswith4chareach".split("(?<=\\G.{4})")
 ));
System.out.println(Arrays.toString(
“Thisismystringi希望拆分为包含4个共享的组”。拆分((?这里需要做的事情很少:

首先,常见的惯例是apon使用大写字母开始变量名,将
I
NewArray
变量分别更改为'I'和'NewArray'

然后,您的代码不起作用,因为您第一次通过循环,
i-3
将导致IndexOutOfBounds异常

最后,不显示如何设置newArray的大小

int sublen = 3; // how many elements in each sub array.
int size = ((bytes.length - 1) / sublen) + 1; // how many newArray members we will need
byte[][] newArray = new byte[size][]; 
int to = byte.length;
int cursor = size - 1;
int from = cursor * sublen;
while (cursor >= 0) {
    newArray[cursor] = Arrays.copyOfRange(bytes, from, to);
    to = from;
    from -= sublen;
    cursor --;
}

如果实际上需要很大的块,并且不想独立地修改它们的内容,可以考虑通过使用<代码> ByteBuffer .Wrp()/<代码>重用相同的初始数组,然后<代码> SLICE()

重复。这将防止不必要的复制和内存浪费。

这是我的实现,它将把数组拆分为子数组,子数组的最大大小由您决定,并将子数组放入数组列表中。如果数组的大小不是所选最大大小的倍数,则最后一个数组将更小

import java.util.Arrays;
...

public static <T> List<T[]> splitArray(T[] items, int maxSubArraySize) {
  List<T[]> result = new ArrayList<T[]>();
  if (items ==null || items.length == 0) {
      return result;
  }

  int from = 0;
  int to = 0;
  int slicedItems = 0;
  while (slicedItems < items.length) {
      to = from + Math.min(maxSubArraySize, items.length - to);
      T[] slice = Arrays.copyOfRange(items, from, to);
      result.add(slice);
      slicedItems += slice.length;
      from = to;
  }
  return result;
}
导入java.util.array;
...
公共静态列表拆分数组(T[]项,int MaxSubraySize){
列表结果=新建ArrayList();
if(items==null | | items.length==0){
返回结果;
}
int from=0;
int到=0;
int-slicedItems=0;
while(slicedItems
这里有一个拆分数组的函数,您可以使用下面的主要方法来测试它

private static List<Integer[]> splitArray(Integer[] originalArray, int chunkSize) {
List<Integer[]> listOfArrays = new ArrayList<Integer[]>();
int totalSize = originalArray.length;
if(totalSize < chunkSize ){
   chunkSize = totalSize;
}
int from = 0;
int to = chunkSize;

while(from < totalSize){
    Integer[] partArray = Arrays.copyOfRange(originalArray, from, to);
    listOfArrays.add(partArray);

    from+= chunkSize;
    to = from + chunkSize;
    if(to>totalSize){
        to = totalSize;
    }
}
return listOfArrays;
}
私有静态列表拆分数组(整数[]originalArray,int chunkSize){
List-listOfArrays=new-ArrayList();
int totalSize=originalArray.length;
if(totalSize总大小){
to=总尺寸;
}
}
返回阵列列表;
}
测试方法:

public static void main(String[] args) {
List<Integer> testingOriginalList = new ArrayList<Integer>();

for(int i=0;i<200;i++){
    testingOriginalList.add(i);
}

int batchSize = 51;
Integer[] originalArray = testingOriginalList.toArray(new Integer[]{});

List<Integer[]> listOfArrays = splitArray(originalArray, batchSize);


for(Integer[] array : listOfArrays){
    System.out.print(array.length + ", ");
    System.out.println(Arrays.toString(array));
}
}
publicstaticvoidmain(字符串[]args){
List testingOriginalList=新建ArrayList();

对于(int i=0;i,这里有一个方便的方法,它将
字节[]
转换为
字节[]
的数组。因此,结果是
字节[]

public byte[][] splitBytes(final byte[] data, final int chunkSize)
{
  final int length = data.length;
  final byte[][] dest = new byte[(length + chunkSize - 1)/chunkSize][];
  int destIndex = 0;
  int stopIndex = 0;

  for (int startIndex = 0; startIndex + chunkSize <= length; startIndex += chunkSize)
  {
    stopIndex += chunkSize;
    dest[destIndex++] = Arrays.copyOfRange(data, startIndex, stopIndex);
  }

  if (stopIndex < length)
    dest[destIndex] = Arrays.copyOfRange(data, stopIndex, length);

  return dest;
}
public byte[]splitBytes(最终byte[]data,最终int chunkSize)
{
最终整数长度=data.length;
最终字节[][]dest=新字节[(长度+chunkSize-1)/chunkSize]];
int destIndex=0;
int stopIndex=0;
对于(int-startIndex=0;startIndex+chunkSize
import java.util.array;
公开课考试{
私家车{
试一试{
byte[]cfsObjIds=“abcdefghij”.getBytes();
System.out.println(Arrays.toString(cfsObjIds));
最终int chunkSize=4;
System.out.println(“按“+chunkSize+”:”)拆分;
int objQty=cfsObjIds.length;
对于(int i=0;i
我知道这个问题已经很老了,但是嘿,有人可以为这个常见问题搜索另一个干净的Java答案。 如果您使用的是List(Java 7),那么有一种非常简单和干净的方法来获取列表的一部分:

使用起来很简单。如果我以问题为例,它会是这样的:

int chunkSize = 3;
int counter = 0;
// bytes must be a List like an ArrayList
List<Byte> byteList = Arrays.asList(bytes);
int length = byteList.size(); 
for (int fromIndex = 0; fromIndex < length; fromIndex += chunkSize) {
   int toIndex = fromIndex + chunkSize;
   if(toIndex > length){
      toIndex = length;
   }
   NewArray[counter] = byteList.subList(fromIndex, toIndex);
   counter++;
}
// Now NewArray[] contain sub array and the last one is of the remaining length
int chunkSize=3;
int计数器=0;
//字节必须是类似于ArrayList的列表
List byteList=Arrays.asList(字节);
int length=byteList.size();
for(int-fromIndex=0;fromIndex长度){
toIndex=长度;
}
NewArray[counter]=byteList.subList(从索引到索引);
计数器++;
}
//现在NewArray[]包含子数组,最后一个是剩余长度的子数组
为了更好地利用“计数器”,一些人还可以改变NewArray的构建方式,例如:

// NewArray must be a List<List<Byte>>
NewArray.addAll(byteList.subList(fromIndex, toIndex));
//NewArray必须是列表
addAll(byteList.subList(fromIndex,toIndex));

希望这将对将来的人有所帮助!

如果您已经在使用字符串或数组很小,这将是可以的。对于大字节数组,转换为字符串和regexp有点困难
// NewArray must be a List<List<Byte>>
NewArray.addAll(byteList.subList(fromIndex, toIndex));