一位数组的初始化(两种方法)
数组类型 数组明[]={值1,值2,值3......值n};
数组类型 数组名[]=new 数据类型[常量值] //这种方法会给所有的数组元素赋予同一个默认值,对数值类型来说,默认值也是0
1.数组的遍历
除了for循环,比较简单的是for-each语句;
格式:for(类型 变量名:数组)
类型:任何数据类型;数组:定义的数组名
{语句}
public class bianli { public static void main(String[] args) { // TODO Auto-generated method stub int a[]={1,2,3,4,5,6,7}; for( int i:a){ System.out.print(i); } } }
运行之后的结果
Ps:直接遍历的方法
Arrays.asList(a)//a是要遍历的目标数组
import java.util.*; public class asList { public static void main(String[] args) { // TODO Auto-generated method stub String[] A={"I","L","O","V","E","J","A","V","A"}; System.out.println("数组A:"+Arrays.asList(A)); } }
2:数组的复制
System.arraycopy(a,b,c,d,e) //a:源数组 b:从哪个位置开始复制 c:目标数组 d:偏移量 e:要从源数组中复制到目标数组元素的个数
public class arraycopy { public static void main(String[] args){ String A[]={"H","e","1","1","0"}; String B[]=new String[6]; System.arraycopy(A, 0, B, 1, B.length-1); for(int i=0;i<B.length;i++){ System.out.print(B[i]+" "); } } }
运行之后的结果
3:填充
Arrays.Fill(a,b) // a:目标数组名 b:要填充的值
import java.util.*; public class tianchong { public static void main(String[] args) { // TODO Auto-generated method stub String[] A=new String[3]; Arrays.fill(A, "I love you"); for(int i=0;i<A.length;i++){ System.out.println(A[i]+" "); } } }
运行之后:
4:相等
Arrays.equals(A,B) //目标数组A 和目标数组B
import java.util.Arrays; public class xiangdeng { public static void main(String[] args) { // TODO Auto-generated method stub String[] A={"a","b","c"}; String[] B={"A","B","C"}; String[] C={"a","b","c"}; System.out.println("数组A和B相等:"+Arrays.equals(A, B)); System.out.println("数组A和c相等:"+Arrays.equals(A, C)); } }
运行之后: