> 文章列表 > Arrays方法(copyOfRange,fill)

Arrays方法(copyOfRange,fill)

Arrays方法(copyOfRange,fill)

Arrays方法

1、Arrays.copyOfRange

Arrays.copyOfRange的使用方法
功能:
数组拷贝至另外一个数组
参数
original:第一个参数为要拷贝的数组对象
from:第二个参数为拷贝的开始位置(包含)
to:第三个参数为拷贝的结束位置(不包含)

String[] source={"a","b","c","d","e","f","g","h","i","j","k","l","m","n"};
String[] x=Arrays.copyOfRange(source,0,13);            //从索引0开始到13,总共14
String[] y=Arrays.copyOfRange(source,6,13);            //从索引6开始到13,总共7
System.out.println(Arrays.toString(x));
System.out.println(Arrays.toString(y));

打印:

[a, b, c, d, e, f, g, h, i, j, k, l, m]
[g, h, i, j, k, l, m]

2、Arrays.fill方法

public static void fill(int[] a, int fromIndex, int toIndex, int val)
Arrays类的fill() 方法是用来输入给定数组中元素值的。
1、两个参数
public static void fill(int[] a, int val):给定一个数组,一个val值
含义为为数组a进行赋值,使得其所有元素值都为val。

        byte[] m=new byte[]{(byte)0x32,(byte)0x32,(byte)0x32,(byte)0x32,(byte)0x32};
        Arrays.fill(m, (byte)0x00);
        System.out.println(Arrays.toString(m));

打印:[0, 0, 0, 0, 0]

2、四个参数
public static void fill(int[] a, int fromIndex, int toIndex, int val):给定一个数组,起始位置fromIndex(包含),末尾位置toIndex(不包含),对范围内的元素进行赋值,示例如下:

byte[] m=new byte[]{(byte)0x32,(byte)0x32,(byte)0x32,(byte)0x32,(byte)0x32};
Arrays.fill(m, 3,5,(byte)0x00);
System.out.println(Arrays.toString(m));

打印:[50, 50, 50, 0, 0]

3、System.arraycopy方法

Java System.arraycopy() is a native static method to copy elements from the source array to the destination array.
Java System.arraycopy()是一种本地静态方法,用于将元素从源数组复制到目标数组。

public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);

src: the source array.   //源数组。
srcPos: source array index from where copy will start  //从其开始复制的源数组索引
dest: the destination array.  //目标数组。
destPos: destination array index from where data will be copied.  //从中复制数据的目标数组索引。
length: the number of elements to copy.  //要复制的元素数。