java二维数组is_java:如何将二维数组拆分为两个二维数组

这篇博客介绍了如何在Java中将一个二维数组在中途点进行分割。首先确定数组的大小,然后找到中间点,接着创建两个新的二维数组并分别复制原始数组的数据。在处理数组长度不均匀的情况下,使用Math.floor()函数确保正确分割。博客还提到了可以使用System.arraycopy()进行更简洁的实现。
摘要由CSDN通过智能技术生成

比方说你有一个字符串,像这样

String[][] array= new String[][]

{

{"a","b","c"},

{"d","e","f"},

{"h","i","j"},

{"k","l","m"}

};

一个二维数组,现在你需要一种方法来这些阵列在中途点分割。让我们得到中间点。找出阵列有多大,然后将其减半。请注意,如果数组长度不是偶数,也必须处理。例如,长度为3.如果是这种情况,我们将使用Math.floor()函数。

int arrayLength = array.length;

int halfWayPoint = Math.floor(arrayLength/2);

//we also need to know howmany elements are in the array

int numberOfElementsInArray = array[0].length;

现在我们有了所有的信息来创建两个二维数组。现在我们必须明确地复制创建和复制数据。

//the length of the first array will be the half way point which we already have

String [][] newArrayA = new String[halfWayPoint][numberOfElementsInArray];

//this copies the data over

for(int i = 0; i < halfWayPoint; i++)

{

newArrayA[i] = array[i];

}

//now create the other array

int newArrayBLength = array.length - halfWayPoint;

String[][] newArrayB = new String[newArrayBLength][numberOfElementsInArray];

/*

* This copies the data over. Notice that the for loop starts a halfWayPoint.

* This is because this is where we left of copying in the first array.

*/

for(int i = halfWayPoint; i < array.length; i++)

{

newArrayB[i] = array[i];

}

而你的成就!现在

,如果你想这样做更好一点,你可以做这样的

int half = Math.floor(array/2);

int numberOfElementsInArray = array[0].length;

String [][] A = new String[half][numberOfElementsInArray];

String [][] B = new String[array.length - half][numberOfElementsInArray];

for(int i = 0; i < array.length; i++)

{

if(i < half)

{

A[i] = array[i];

}

else

{

B[i] = array[i];

}

}

最后,如果你不想明确做到这一点,你可以使用内置的功能。 System.arraycopy()就是一个例子。这是一个链接到它的api System.arraycopy()

int half = Math.floor(array/2);

int numberOfElementsInArray = array[0].length;

String [][] A = new String[half][numberOfElementsInArray];

String [][] B = new String[array.length - half][numberOfElementsInArray];

System.arraycopy(array,0,A,0,half);

System.arraycopy(array,half,B,0,array.length - half);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值