7.Arrays数组的工具类

Arrays类:
  1. 数组的工具类java.util.Arrays
  2. 由于数组对象本身并没有什么方法可以供我们调用,但API中提供了一个工具类Arrays供我们使用,从而可以对数据对象进行一些基本的操作。
  3. 查看JDK帮助文档
  4. Arrays类中的方法都是static修饰的静态方法,在使用的时候可以直接使用类名进行调用,而"不用"使用对象来调用(注意:是"不用"而不是"不能")
 
具有以下常用功能:
给数组赋值:通过 fill 方法
对数组进行排序:通过 sort 方法,按升序
比较数组:通过 equals 方法比较数组中的元素是否相等
查找数组元素:通过 binarySearch 方法能对排序好的数组进行二分查找法操作
 1 package com.duan.array;
 2 
 3 import java.util.Arrays;
 4 
 5 public class ArraysDemo06 {
 6     public static void main(String[] args) {
 7         int[] a = {1, 2, 3, 4, 5, 678, 2, 2345};
 8 
 9         System.out.println(a);//[I@1540e19d
10 
11         //打印数组元素Arrays.toString
12         System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 5, 678, 2, 2345]
13         printArrays(a);//[1, 2, 3, 4, 5, 678, 2, 2345]
14         //数组进行排序
15         Arrays.sort(a);
16         System.out.println();
17         System.out.println(Arrays.toString(a));//[1, 2, 2, 3, 4, 5, 678, 2345]
18 
19         //填充
20         Arrays.fill(a,0);
21         System.out.println(Arrays.toString(a));//[0, 0, 0, 0, 0, 0, 0, 0]
22     }
23 
24     public static void printArrays(int[] a) {
25         for (int i = 0; i < a.length; i++) {
26             if (i == 0) {
27                 System.out.print("[");
28             }
29             if (i == a.length - 1) {
30                 System.out.print(a[i] + "]");
31             } else {
32                 System.out.print(a[i] + ", ");
33             }
34         }
35     }
36 }
37 
38 结果:
39 [I@1540e19d
40 [1, 2, 3, 4, 5, 678, 2, 2345]
41 [1, 2, 3, 4, 5, 678, 2, 2345]
42 [1, 2, 2, 3, 4, 5, 678, 2345]
43 [0, 0, 0, 0, 0, 0, 0, 0]
原文地址:https://www.cnblogs.com/duanfu/p/12222380.html