数组

2020-11-23  本文已影响0人  冯宏志

数组

一维数组
package com.atguigu.contact;

public class ArrayTest { 
    public static void main(String[] args) {
        int[] ids;  //声明
        ids = new int[]{1001,1002,1003,1004};//静态初始化。初始化和赋值同时进行
        String[] names = new String[5];//动态初始化,初始化和赋值分开进行
        //对数组赋值     
        names[0] = "小明";
        names[1] = "小红";
        names[2] = "小军";
        names[3] = "小方";
        //获取数组长度            
        System.out.println(ids.length);
        //遍历数组元素
        for(int i = 0;i < names.length;i++)
            System.out.println(names[i]);
    }

}

总结:数组一旦初始化完成,其长度确定

二维数组
package com.atguigu.contact;

public class ArrayTest1 {
    public static void main(String[] args) {
        //静态初始化
        int[][] arr = new int[][] {{1,2,3},{4,5},{6,7,8}};
        //动态初始化1
        int[][] arr1 = new int[3][2];
        //动态初始化2
        int[][] arr2 = new int[3][];
        //错误的情况
//      String [][] arr3 = new String[][3];
//      String [4][3] arr4 = new String[][];
//      int [][] arr5 = new int[4][3] {{1,,2,3},{4,5},{6,7,8}};
    }
}
 
深复制与浅复制
package com.atguigu.contact;

public class ArrayTest2 {
    public static void main(String[] args) {
        int[] array1,array2,array3;
        array1 = new int[]{1,2,3,4,5};
        //  浅复制
        array2 = array1;
        array1[0] = 10;
        for(int i = 0;i<array1.length;i++)
        {
            System.out.print(array1[i]);//10 2 3 4 5
            System.out.print(array2[i]);//10 2 3 4 5
        }
        array3 = new int[array1.length];
        //  深复制 
        for(int i = 0;i<array1.length;i++)
        {
            array3[i] = array1[i];
            System.out.println(array3[i]);
        }
    } 
}

Arrays工具类的使用

package com.atguigu.contact;

import java.util.Arrays;

public class ArrayTest3 {
    public static void main(String[] args) {
        //boolean equals(int[] a,int[] b)判断两数组是否相等
        int[] arr1 = new int[]{1,2,3,4};
        int[] arr2 = new int[]{1,3,2,4};
        boolean isEqual = Arrays.equals(arr1, arr2);
        System.out.println(isEqual);//false
        //String toString(int[] a)输出数组信息
        System.out.println(Arrays.toString(arr1));//[1, 2, 3, 4]
        //void fill(int[] a,int val)将指定值填充到数组之中
        Arrays.fill(arr1, 5);
        System.out.println(Arrays.toString(arr1));//[5, 5, 5, 5]
        //void sort(int[] a)对数组进行排序
        int[] arr3 = new int[] {5,3,6,7,8,1,10};
        Arrays.sort(arr3);
        System.out.println(Arrays.toString(arr3));//[1, 3, 5, 6, 7, 8, 10]
        //int binarySearch(int[] a,int key)对排序后的数组进行二分法检索指定的值
        System.out.println(Arrays.binarySearch(arr3, 3));
    }
}

数组常见异常

1.数组角标越界异常:ArrayIndexOutOfBoundsException
2.空指针异常:NullPointerException


image.png
上一篇 下一篇

猜你喜欢

热点阅读