我的身旁是一扇亮了又暗的窗

0%

Arrays类

概述

java.util.Arrays此类包含用来操作数组的各种方法,比如排序和搜索等。其所有方法均为静态方法,调用起来非常简单。

操作数组的方法

  • public static String toString(int[] a):返回指定数组内容的字符串表示形式

  • public static void sort(int[] a):对指定的数组按数字升序进行排序

    • 数值,sort默认按照升序从小到大
  • 字符串,sort默认按照字母升序

    • 自定义类型,自定义类需要有Comparable或者Comparator接口的支持
  • 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public static void main(String[] args) {
byte[] bytes = {99,98,97};
short[] shorts = {99,98,97};
int[] ints ={99,98,97};
long[] longs = {99,98,97};
float[] floats = {99.0F,98.0F,97.0F};
double[] doubles = {99.0,98.0,97.0};
char[] chars = {'c','b','a'};
boolean[] booleans = {true,false,true};
String[] strings = {"c","b","a"};
// Arrays.toString
System.out.println(Arrays.toString(bytes)); //[99, 98, 97]
System.out.println(Arrays.toString(shorts)); //[99, 98, 97]
System.out.println(Arrays.toString(ints)); //[99, 98, 97]
System.out.println(Arrays.toString(longs)); //[99, 98, 97]
System.out.println(Arrays.toString(chars)); //[c, b, a]
System.out.println(Arrays.toString(floats)); //[99.0, 98.0, 97.0]
System.out.println(Arrays.toString(doubles)); //[99.0, 98.0, 97.0]
System.out.println(Arrays.toString(booleans)); //[true, false, true]
System.out.println(Arrays.toString(strings)); //[c, b, a]
// Arrays.sort
Arrays.sort(bytes);
Arrays.sort(shorts);
Arrays.sort(ints);
Arrays.sort(longs);
Arrays.sort(chars);
Arrays.sort(floats);
Arrays.sort(doubles);
Arrays.sort(strings);
System.out.println("====================");
System.out.println(Arrays.toString(bytes)); //[97, 98, 99]
System.out.println(Arrays.toString(shorts)); //[97, 98, 99]
System.out.println(Arrays.toString(ints)); //[97, 98, 99]
System.out.println(Arrays.toString(longs)); //[97, 98, 99]
System.out.println(Arrays.toString(chars)); //[a, b, c]
System.out.println(Arrays.toString(floats)); //[97.0, 98.0, 99.0]
System.out.println(Arrays.toString(doubles)); //[97.0, 98.0, 99.0]
System.out.println(Arrays.toString(strings)); //[a, b, c]
}