Java数组

数组操作指南
1.数组的遍历(for each循环)
//打印数组a的每一个元素,一个元素占一行
for(int element : a)
	System.out.println(element);
2.数组的初始化
	/**
	out: 2 3 5 7 11 13 
		[17, 19, 23, 29, 31, 37]
	*/
	int[] smallPrimes = {2, 3, 5, 7, 11, 13};
	for(int element : smallPrimes)
		System.out.print(element + " ");
	System.out.println();
	smallPrimes = new int[] {17, 19, 23, 29, 31, 37};  //数组重新初始化
	System.out.println(Arrays.toString(smallPrimes));  //打印成数组样式
3.数组拷贝

①使用“=”符号,两个数组变量将引用同一个数组
②使用Arrays.copyOf()方法,将一个数组的所有值拷贝到一个新的数组

	//第二个参数是新数组的长度,若大于旧数组的长度,多余元素赋0或false,若小于则取前面的元素
	int[] a = Arrays.copyOf(b, b.length);
4.java.util.Arrays常用方法
  • static String toString( type[] a) //见上例
  • static type copyOf( type[] a, int length) //见上例
  • static type copyOfRange( type[] a, int start, int end) //同上,从start下标开始,end结束(不包括这一个)
  • static void sort( type[] a) //快速排序算法排序
  • static int binarySearch( type[] a, int start, int end, type v) //采用二分搜索算法查找值v,成功返回下标,失败返回负数
  • static void fill( type[] a, type v) //将数组所有元素值设置为v
  • static boolean equals( type[] a, type[] b) //比较两个数组是否相等
5.二维数组
		int[][] ary = new int[3][]; //二维数组声明
		ary = new int[][] { //二维数组初始化
			{3,2,1},
			{5,6,8},
			{5,9,7}
		};
		System.out.println(Arrays.deepToString(ary)); //输出二维数组类似toString()
		for(int i=0; i<3; i++)
			for(int j=0; j<3; j++)
				ary[i][j] = (int)(random()*100);
		System.out.println(Arrays.deepToString(ary));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值