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] + ", ");
}
}
}
}