Chapter 19 Arrays Array Tool Class
19.1 Overview:
- java.util.Arrays is a tool class related to arrays, which provides a large number of static methods to implement common operations on arrays.
19.2 Program an array of parameters to a string
Output format: [element1, element2, ...]
public static String toString(数组)
import java.util.Arrays;
public class DemoArrays {
public static void main(String[] args) {
int[] intArr = {
1, 2, 3 };
String intStr = Arrays.toString(intArr);
System.out.println(intStr);//[1, 2, 3]
}
}
19.3 Sorting the parameter array
- Sorts the elements of the array in the default ascending order.
- If it is a value, sort defaults to ascending order from small to large
- If it is a string, sort defaults to ascending alphabetical order
- If it is a custom type, then this custom class needs to be supported by the Comparable or Comparator interface.
public static void sort(数组)
import java.util.Arrays;
public class DemoArrays {
public static void main(String[] args) {
int[] array = {
2, 1, 3, 6, 8 };
Arrays.sort(array);
System.out.println(Arrays.toString(array));//[1, 2, 3, 6, 8]
}
}
19.4 Exercises
import java.util.Arrays;
/*
将一个随机字符串中的所有字符升序排列,并且倒序打印
*/
public class Demo03ArraysTest {
public static void main(String[] args) {
String str = "asdiugfrqgbbvwierhisdf";
char[] chars = str.toCharArray();
Arrays.sort(chars);
//IDEA快捷输入chars.forr
for (int i = chars.length - 1; i >= 0; i--) //反向遍历打印
System.out.print(chars[i] + " ");
}
}
}