数组扩容复制的方式

数组扩容复制的方式
public class TestCopyArray{    
    public static void main(String[] args) {
 
    int[] nums = new int[5];//数组创建之后,⻓度不可变        
        nums[0] = 11;    
        nums[1] = 22;    
        nums[2] = 33;    
        nums[3] = 44;    
        nums[4] = 55; 
        
        //1.创建⽐原数组⼤的新数组    
        int[] newNums = new int[ nums.length * 2 ];        
        //2.复制原数组中的所有数据到新数组    
        for(int i = 0 ; i < nums.length ; i++){      
            newNums[i] = nums[i];    
        }
 
        //遍历原数组    
        for(int i = 0 ; i < nums.length ; i++){      
            System.out.print( nums[i] +"\t");    
        }    
        System.out.println();        
        //遍历新数组    
        for(int i = 0 ; i < newNums.length ; i++){      
            System.out.print( newNums[i] +"\t");    
        }      
    } 
}
 
public class TestCopyArray2{    
    public static void main(String[] args){        
        int[] nums = new int[5];//数组创建之后,⻓度不可变        
        nums[0] = 11;    
        nums[1] = 22;    
        nums[2] = 33;    
        nums[3] = 44;    
        nums[4] = 55;     
        
        
        //复制的赋值   
        
        //1.创建新数组    
        int[] newNums = new int[ nums.length * 2 ];            
        //2.使⽤System.arraycopy(原数组,原数组起始下标,新数组,新数组的起始存储下标,需要赋值的个数或⻓度);    
        System.arraycopy( nums , 0 , newNums , 0 , nums.length);    
 
   		//遍历新数组    
        for(int i = 0 ; i < newNums.length ; i++){      
            System.out.print( newNums[i] +"\t");    
        }      
    } 
}
import java.util.Arrays;
 
public class TestCopyArray3{    
    public static void main(String[] args){        
        int[] nums = new int[5];
        //数组创建之后,⻓度不可变        
        nums[0] = 11;
        nums[1] = 22;    
        nums[2] = 33;    
        nums[3] = 44;    
        nums[4] = 55;    
        
        //1.创建新数组、复制元素    
        int[] newNums = java.util.Arrays.copyOf(nums , nums.length * 2);//将带有原值的新数组返回给我们 
        
        
        //2.遍历    
        for(int i = 0 ; i < newNums.length ; i++){      
            System.out.print( newNums[i] +"\t");    
        }  
    } 
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值