一维数组:
1、数组的声明与初始化
2、调用数组的指定位置的元素
3、获取数组长度
4、遍历数组
5、数组元素的默认化初始值
class project{
public static void main(String[] arg){
int[] ids; //声明
ids = new int[]{1,2,3,4};//静态初始化:数组初始化+数组赋值
String[] names = new String[4]; //动态初始化:数组初始化(指定了数组长度)
names[0] = "marry";
names[1] = "jerry";
names[2] = "henry";
names[3] = "ali";
System.out.println(names.length); //属性length 获取数组长度
//遍历数组
for (int i = 0; i < names.length; i++){
System.out.println(names[i]);
}
}
}
class project{
public static void main(String[] arg){
int[] arr = new int[2];
for (int j = 0; j < arr.length; j++){
System.out.println(arr[j]); //初始值:0
}
boolean[] arr1 = new boolean[2];
for (int i = 0; i<arr1.length;i++){
System.out.println(arr1[i]); //初始值:false
}
float[] arr2 = new float[2];
for (int j = 0; j < arr2.length; j++){
System.out.println(arr2[j]);} //初始值:0.0
}
}
二维数组:
class project {
public static void main(String[] arg) {
int[][] arr = new int[][]{{1,2,3},{9},{2}}; //静态初始化数组
int[][] arr1 = new int[4][5]; //动态初始化二维数组
System.out.println(arr1.length); //获取数组长度,返回4
System.out.println(arr1[0].length); //返回0维元素个数
}
}
Arrays工具类的使用
1、boolean equals(int[] a,int[] b)
2、String toString(int[] a)
3、void fill(int[] a,int val)
4、void sort(int[] a)
5、int binarySearch(int[] a,int key)
class project {
public static void main(String[] arg) {
int[] arr1 = new int[]{1,4,7,8};
int[] arr2 = new int[]{3,0,1,8};
boolean isEqual = Arrays.equals(arr1,arr2); //Arrays.equals(int[] a,int[] b)判断两个数组是否相等
System.out.println(isEqual);
System.out.println(Arrays.toString(arr1)); //Arrays.toString(int[] a)输出数组信息
Arrays.fill(arr1,33); //用指定值填充数组(即替换)
System.out.println(Arrays.toString(arr1));
Arrays.sort(arr2); //Arrays.sort(int[] a) 对数组排序
System.out.println(Arrays.toString(arr1));
int index = Arrays.binarySearch(arr2,1); //Arrays.binarySearch(int[] a,value)对排序好的数组进行二分查找,返回所在索引
System.out.println(index);
}
}