栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

对Java中数组的理解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

对Java中数组的理解

1.何为数组?

数组的作用是为了存放一组数据类型相同的数据.

2.数组的参数

1)元素:指数组中存放的单个数据

2)数组长度:指数组中数据的个数

3)元素下标:指元素在数组中的位置,以0开始,最后一个元素的下标为数组名.length-1

3.数组的创建与使用

1)声明: 数据类型[] 数组名;

2)创建

动态创建(两种)

数组名 =new [数组长度] ;默认数组元素为0

数组名= new 数据类型[]{元素1,元素2,.......} ;

静态创建(1种,要求声明和创建必须在同一行)

数据类型[] 数组名 = {元素1,元素2,元素3.......} ;

3.数组的使用

1)获取长度: 数组名.length

2)改值:数组名[下标] = 新值

3)获取元素: 数组名[下标]

4.遍历(将数据一个个取出来)两种方法
1)foreach(数据类型 变量名:数组名) ;
   public class Arra {
	public static void main(String[] args) {
		int[] arr = {12,13,14,15,16,17} ;
		for (int x : arr) {
			System.out.print(x+" ");
		}
	}
}
2)使用for循环
public class Arra1 {
	public static void main(String[] args) {
		int[] arr = {12,13,14,15,16,17} ;
		for (int i = 0; i < arr.length; i++) {
       //将取出的元素赋值给想;
			int x= arr[i] ;
    //循环一次输出一次
		System.out.println(x);	
		}
	}
}
5.查找数据是否存在于数组
public class Reach {
	
	public static void main(String[] args) {
		int[] arr = {12,13,14,15,16,17} ;
		int b = 17 ;
		//传参
		find(arr,b);
	}
	//因为方法的作用是判断一个数是否存在于数组,因此形参需要数组和数
	public static void find(int[] nums,int nu) {
		//用形参进行遍历
		for (int x : nums) {
			//用形参判断
			if(nu == x) {
				System.out.println("该数存在");
				return ;//若存在结束方法
				}//遍历完,即循环结束后输出不存在
			}System.out.println("不存在");
		}
}

总结:若要使用带有形参列表的方法,则在方法体中参与运算 判断功能的一定是形参.

6.数组拷贝(将一个数组的元素copy给新的数组)

1)要求:新数组的长度与旧数组必须相同

2)步骤:

  1.存在老数组A

  2.创建新数组B

   3.遍历出A中的元素

   4.将A中遍历出的元素赋值给数组B

public class Copy {
	public static void main(String[] args) {
		int[] A = {12,14,17,19,20};
		//B的长度调用A.length
		int[] B =new int[A.length];
		//
		for (int i = 0; i < B.length; i++) {
			//A[i]使用A中的第i个元素赋值给B中对应的位置
			B[i] = A[i] ;
		}
			//此时已经将A的元素赋值给了B,若要打印B的元素,需将B的元素取出后进行逐个打印
			//因此在此直接System.out.println(B)是为错误
		for (int j : B) {
			System.out.println(j);
			}
		}
	}
7.扩容

1)要求新数组B的长度必须大于需要扩容的数组A

2)步骤

        1.创建旧数组A

        2.创建扩容的新数组B(要求数组B的长度大于A的长度)

        3.将A中的元素遍历出来

        4.将A中遍历的元素放到B中对应位置

        5.将数组B赋给数组A

public class Englarge {
	public static void main(String[] args) {
		int[] A = {12,14,17,19,20};
		int[] B = new int[A.length+10] ;
		for (int i = 0; i < A.length; i++) {
			B[i] = A[i] ;
		}
		A = B ;
		for (int j : A) {
			
			System.out.println(j);
		}
	}
}

总结:for循环中i

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/921496.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号