本文目录一览:
java中如何把一个int型数组分解成两个int型数组啊?
arraycopy(Object
src,
int
srcPos,
Object
dest,
int
destPos,
int
length)
从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
例子如下:
int[]
c
=
{1,2,3,4}
int[]
a
=
System.arraycopy(a,0,2);
int[]
b
=
System.arraycopy(a,2,4);
java 怎么将一个数组拆分成两个数组
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] str = { "112", "2321", "3231", "4443", "5321" };
String[] sub1 = Arrays.copyOf(str, 3);
String[] sub2 = Arrays.copyOfRange(str, 3, str.length);
System.out.println(Arrays.deepToString(sub1));
System.out.println(Arrays.deepToString(sub2));
}
}
运行结果
java 怎么将一个数组拆分成两个数组?
package Test20201227;
import java.util.Arrays;
public class Test03 {
public static void main(String[] args) {
//待拆分的A数组
int a[] = {1,2,3,4,5,6,7,8,9,10};
//新数组长度:先定义为a数组长度的一般,如果有剩余可以再取值!
int newArrayLength = a.length/2;
//接收拆分的bc数组
int b[] = new int[a.length/2];
int c[] = new int[a.length/2];
int k = 0;//k用来记录a的下标;
for(int i=0;inewArrayLength;i++){
b[i] = a[k];
k++;
c[i] = a[k];
k++;
}
//如果a数组有多余的值再取出
//判断余数
int remainder = a.length%2;
if(remainder!=0){
//a数组多一个,则给b数组扩容,
b = Arrays.copyOf(b, b.length+1);
b[b.length-1] = a[k];
}
//查看结果
System.out.println("a数组(待拆分数组): "+Arrays.toString(a));
System.out.println("b数组(拆分后第一数组): "+Arrays.toString(b));
System.out.println("c数组(拆分后第二数组): "+Arrays.toString(c));
}
}