Java(109):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.copyOf

Arrays的copyOf()方法传回的数组是新的数组对象,改变传回数组中的元素值,不会影响原来的数组。

copyOf()的第二个自变量指定要建立的新数组长度,如果新数组的长度超过原数组的长度,则保留数组默认值,例如:

int[] arr1 = {1, 2, 3, 4, 5,6,7,8,9,10};
int[] arr2 = Arrays.copyOf(arr1, 5);
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

例如:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]

3、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]

4、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.  //要复制的元素数。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宁宁可可

您的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值