2024.1.3总结

数组

一维数组

静态声明(适用于已知数据的情况)

方式一  int[] arr1 = {1,2,3,4,5,6,7,8,9};

方式二  int[] arr2 = new int[]{1,2,3,4,5,6,7,8,9};

动态声明(适用于不确定每个元素的情况)

int[] arr3 = new int[8];

获取数组中的某一个元素

System.out.println(arr1[3]);

更改数组中的某一个元素

arr1[2] = 999;

遍历数组

for(int i = 0;i < arr1.length;i++)

        System.out.println(arr1[i]);

数组的替换复制

是指将源数组中的某部分数据元素覆盖到目标数组中的某位置

//src 源数组  srcIndex源数组起始索引
		//dest 目标数组  destIndex目标数组起始索引
		//length 要复制的个数
	
	public static void main(String[] args) {
		int[] src = {1,2,3,4,5,6,7,8,9};
		int[] dest = {90,91,92,93,94,95,96,97,98,99,100,101,102};
		int srcIndex = 3;
		int destIndex = 4;
		int length = 2;
		
		System.arraycopy(src,srcIndex,dest,destIndex,length);  //将源数组中索引为3开始的两个元素复制到目标数组中索引从4开始的两个位置上
		
		for (int i = 0; i < dest.length; i++) {	//打印
			System.out.print(dest[i]+"  ");	//得到的是  90  91  92  93  4  5  96  97  98  99  100  101  102  
		}
	}
数组的插入复制

是指将原数组中的某部分数据元素,插入到目标数组的某个位置,得到一个新的数组


	public static int[] Insert_copy(int[] src,int scrIndex,int[] dest,int destIndex ,int length){
		int[] NewDest = new int[dest.length + length];  //新的数组长度是  目标数组加上要插入的元素的个数
		
		for(int i = 0;i <= destIndex;i++)	//将目标数组的索引之前的元素先存入新的数组中
			NewDest[i] = dest[i];
		
		int NewIndex = destIndex + 1;    //记录新数组当前的索引位置
		for(int i = scrIndex;i < scrIndex + length;i++){  //将原数组中从索引位置开始的length个元素插入到新数组中
			NewDest[NewIndex] = src[i];
			NewIndex++;
		}
		
		for(int i = destIndex + 1;i < dest.length;i++){		//将目标数组中剩余的元素插入到新的数组之中
			NewDest[NewIndex] = dest[i];
			NewIndex++;
		}
		return NewDest;		//返回新数组
	}
	
		
	
	
	public static void main(String[] args) {
		int[] src = {1,2,3,4,5,6,7,8,9};
		int[] dest = {90,91,92,93,94,95,96,97,98,99,100,101,102};
		int srcIndex = 1;
		int destIndex = 5;
		int length = 4;
		
		int[] New__ = Insert_copy(src, srcIndex, dest, destIndex, length);  //调用
		
		for (int i = 0; i < New__.length; i++) {
			System.out.print(New__[i]+"  ");     //输出新的数组 得到  90  91  92  93  94  95  2  3  4  5  96  97  98  99  100  101  102 
		}
	}
二维数组

二维数组中的每个数据就是一个一维数组

静态声明

方式一   int[][] arr1 = {{1,2,3,4,5},{234,32},{2323,444,634,123}};

方式二   int[][] arr2 = new int[][]{{1,2},(233,250,1314)};

动态声明

int[][] arr3 = new int[5][8];

//意思是 这个二维数组中共有5个一维数组,其中每个一维数组的长度都为8

二维数组的遍历

for(int i = 0;i < arr1.length;i++)

        for(int j = 0;j < arr1[i].length;j++)

                System.out.println(arr[i][j]);

二维数组的锯齿状

涉及的知识点是,在声明二维数组时,可以不声明每一个一维数组的长度

//二维数组锯齿状
	//动态定义二维数组的时候,可以不写每个一维数组的元素个数
	//内部每一个一维数组的长度需要单独定义
	public static void main(String[] args) {
		
		String[][] arr1 = new String[4][];
			
		//对二维数组中的每一个一维数组声明长度
		for(int i = 0;i < arr1.length;i++)
			arr1[i] = new String[i+1];
		
	}

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值