java数组使用 六 Arrays类


package array;

import java.util.Arrays;

public class Demo06 {

    final static int[] a = {1, 2, 13, 45, 45, 8, 4, 5465, 46, 54, 564, 1, 999, 54, 1, 54, 121, 345, 51,};

    public static void main(String[] args) {

        test();

        Demo06 demo06 = new Demo06();
        demo06.printArray(a);//[1, 2, 13, 45, 45, 8, 4, 5465, 46, 54, 564, 1, 999, 54, 1, 54, 121, 345, 51]

        System.out.println();
//        数组 排序  升序;
        Arrays.sort(a);
        System.out.println("数组 排序:" + Arrays.toString(a));//[1, 1, 1, 2, 4, 8, 13, 45, 45, 46, 51, 54, 54, 54, 121, 345, 564, 999, 5465]

//        数组 3到6之间被 0 填充;
        Arrays.fill(a, 3, 6, 0);
        System.out.println("数组 3到6之间被 0  填充:" + Arrays.toString(a));//[1, 1, 1, 0, 0, 0, 13, 45, 45, 46, 51, 54, 54, 54, 121, 345, 564, 999, 5465]

        //        数组  填充;
        Arrays.fill(a, 0);
        System.out.println("数组 填充:" + Arrays.toString(a));//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        test1();

    }

    public static void test1() {
        //        数组  填充;
        Arrays.fill(a, 0);
        System.out.println("数组 填充:" + Arrays.toString(a));//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    }


    public static void test() {
//        是一个对象 hascode
        System.out.print("是一个对象 hascod码:" + a + "\t"); //[I@1b6d3586 -----hascode
        System.out.println();
//        输出所有数组元素;Arrays.toString(a)
        System.out.print("输出所有数组元素:" + Arrays.toString(a) + "\t");//[1, 2, 13, 45, 45, 8, 4, 5465, 46, 54, 564, 1, 999, 54, 1, 54, 121, 345, 51]
        System.out.println();
    }


    public void printArray(int[] a) {
        for (int i = 0; i < a.length; i++) {
            if (i == 0) {
                System.out.print("循环输出所有数组元素:[");
            }
            if (i == a.length - 1) {

                System.out.print(a[i] + "]");
            } else {
                System.out.print(a[i] + ", ");
            }
        }
//        [1,2,13,45,45,8,4,5465,46,54,564,1,999,54,1,54,121,345,51]
    }
}

运行结果

posted @ 2021-07-30 18:03  阿向向  阅读(38)  评论(0编辑  收藏  举报