kuangshenshuo-数组-Arrays类

Arrays类

  • java.util.Arrays(查看API文档)

    • This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.
    • The methods in this class all throw a NullPointerException, if the specified array reference is null, except where noted.
    • The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)
  • Arrays类中提供的方法都是static修饰的静态方法,在使用时可以直接使用类名进行调用;

  • 常用功能:

    • 赋值: public static void fill(int[] a, int val)
    • 排序: public static void sort(int[] a)
    • 比较:public static boolean equals(int[] a1, int[] a2)
    • 查找数组元素: public static int binarySearch(int[] a, int key)

示例:

import java.util.Arrays;

public class ArraysTest {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,999,31442,6,65,768,23};

        System.out.println(a);  //[I@1b6d3586  --> 对象的hash code

        //打印数组元素 Arrays.toString()
        System.out.println(Arrays.toString(a)); // [1, 2, 3, 4, 999, 31442, 6, 65, 768, 23]
        //自己写的方法
        printArray(a); //运行结果一致

        //数组排序:Arrays.sort() 升序
        Arrays.sort(a);
        System.out.println(Arrays.toString(a)); //[1, 2, 3, 4, 6, 23, 65, 768, 999, 31442]

        //数组填充:Arrays.fill()
        Arrays.fill(a, 2,4,0);
        System.out.println(Arrays.toString(a)); //[1, 2, 0, 0, 6, 23, 65, 768, 999, 31442]

        Arrays.fill(a,0);
        System.out.println(Arrays.toString(a)); //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    }

    public static 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.println(a[i] + "]");
            }else{
                System.out.print(a[i] + ", ");
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值