赞助

创建数组时,必须显示指定长度,并在创建之后不可更改长度

扩容的思路:

创建大于原数组长度的新数组

将原数组中的元素依次复制到新数组中

 

 

复制方式 

循环将原数组中所有元素逐一赋值给新数组

pubilc class Test{
  public static void main(String[] args){
  int [] nums = new int[5]
  nums[0] = 1
 nums[0] = 2
nums[0] =3
 nums[0] = 4
 nums[0] = 5
//创建比原数组还大的数组
int [] bigArr = new int[nums.length + 2];//*2 
for(int i = 0;i<nums.length;i++){
System.out.print(nums[i])
 bigArr[i] = nums[i]
}
}
}

  System.arraycopy(原数组,原数组起始,新数组,新数组起始,长度)

pubilc class Test{
  public static void main(String[] args){
  int [] nums = new int[5]
  nums[0] = 1
  nums[0] = 2
  nums[0] =3
  nums[0] = 4
  nums[0] = 5
//创建比原数组还大的数组
int [] newsArr = new int[];
int [] newsArrs = System.arraycopy(nums,0,newsArr,0,nums.length * 2) } } 

  java.util.Arrays.copyOf(原数组,新长度);//返回带有原值的新数组

pubilc class Test{
  public static void main(String[] args){
  int [] nums = new int[5]
  nums[0] = 1
  nums[0] = 2
  nums[0] =3
  nums[0] = 4
  nums[0] = 5
//创建比原数组还大的数组
int [] newsArr = java.util.Arrays.copyOf(nums,nums.length * 2);
}
}

  

posted on 2022-04-16 19:34  Tsunami黄嵩粟  阅读(96)  评论(0)    收藏  举报