欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Arrays类的用法详述

程序员文章站 2022-09-24 19:56:45
java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的。例子如下:import java.util.Arrays;public class Test3 { public static void main(String[] args) { int [] nums = {6,9,8,4,2}; Arrays.sort(nums); System.out.println("------升序-----");...

java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的。
Arrays类的用法详述
例子如下:

import java.util.Arrays;

public class Test3 {
    public static void main(String[] args) {
        int [] nums = {6,9,8,4,2};
        Arrays.sort(nums);
        System.out.println("------升序-----");
        for (int num : nums) {
            System.out.print(num+"");
        }

        System.out.println("\n------降序-----");
        for (int i = nums.length-1; i >=0 ; i--) {
            System.out.print(nums[i]+"");
        }

        System.out.println("\n------字符串排序-----");
        String [] mm = {"n","1","6","M","a","5"};
        Arrays.sort(mm);
        for (String s : mm) {
            System.out.print(s);
        }

        System.out.println("\n------判断两个数组是否相等-----");
        int [ ] num1 = {1,2,3};
        int [ ] num2 = {1,2,4};
        boolean b = Arrays.equals(num1, num2);
        System.out.print(b);

        System.out.println("\n------转换为字符串-----");
        int [] num3 = {5,6,4,5,8};
        String s = Arrays.toString(num3);
        System.out.print(s);

        System.out.println("\n------赋值相同数值-----");
        int [ ] num4 = {1,2,4};
        Arrays.fill(num4,66);
        for (int i : num4) {
            System.out.print(i+" ");
        }

        System.out.println("\n------复制为新数组-----");
        int [ ] num5 = {1,2,4};
        int[] num55 = Arrays.copyOf(num5, 5);
        for (int i : num55) {
            System.out.print(i);
        }

        System.out.println("\n------查询元素下标-----");
        int [ ] num6 = {1,2,4};
        int i = Arrays.binarySearch(num6, 4);
        System.out.println(i);
    }
}

运行结果如下:
Arrays类的用法详述

本文地址:https://blog.csdn.net/qq_43928469/article/details/109939344