本文最后更新于 2024年11月30日 下午
数组
创建方式
1 2 3 4
| NewClass[] a; NewClass[] b = new NewClass[10]; NewClass[] c = {new NewClass(), new NewClass(), new NewClass()}; NewClass[] p = new NewClass{new NewClass(), new NewClass(), new NewClass(), new NewClass()};
|
返回数组
多维数组
1 2 3 4
| int[][] b = { {1,2,3}, {4,5,6}, };
|
Arrays实用功能
1
| import java.util.Arrays;
|
fill()
以单个元素填充数组
1 2 3 4
| int[] m1 = new int[4]; Arrays.fill(m1,1); System.out.println(Arrays.toString(m1));
|
sort()
1 2 3 4 5
| int[] s1 = new int[]{9,8,7,34,5,2,6,7,10}; Arrays.sort(s1); System.out.println(Arrays.toString(s1));
|
equals() & deepEquals()
1 2 3 4 5 6 7 8
| int[] a1 = new int[]{1,9,10086}; int[] a2 = new int[]{1,9,10086}; System.out.println(Arrays.equals(a1,a2));
int[][] deep1 = new int[][]{ {1,2},{3,4},{5,6} }; int[][] deep2 = new int[][]{ {1,2},{3,4},{5,6} }; System.out.println(Arrays.deepEquals(deep1, deep2));
|
copyOf() & copyOfRange()
复制数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| int[] org = new int[]{8,9,7,721}; int[] des = Arrays.copyOf(org,4); System.out.println(Arrays.toString(des));
int[] org = new int[]{8,9,7,721}; int[] des = Arrays.copyOf(org,3); System.out.println(Arrays.toString(des));
int[] org = new int[]{8,9,7,721}; int[] des = Arrays.copyOf(org,9); System.out.println(Arrays.toString(des));
|
toString() & deepToString()
方便打印数组
1 2 3 4 5 6
| int[] p1 = new int[]{1,2,3}; int[][] d1 = new int[][]{{1,2},{3,4},{5,6}}; System.out.println(Arrays.toString(p1)); System.out.println(Arrays.deepToString(d1));
|
binarySearch()
二分法查找,类同于Python中的bisect.bisect_left()
1 2 3 4 5 6
| int[] pos = new int[]{90,8,7,1,3,5,6,76,5,4,78,67,54,34}; Arrays.sort(pos); System.out.println(Arrays.toString(pos)); System.out.println(Arrays.binarySearch(pos,78));
|
asList()
常用于声明对象组成的列表
1 2 3 4 5 6 7 8
| List<Integer> l1 = Arrays.asList(1,2,3); System.out.println(l1);
List<Student> l2 = Arrays.asList( new Student("xiaoming",21), new Student("xiaomei",19)); System.out.println(l2);
|
setAll()
使用提供的生成器函数设置指定数组的所有元素以计算每个元素
1 2 3
| Set<Integer>[] s = new HashSet[maxlen]; Arrays.setAll(s, i ->new HashSet<Integer>()); s[0].add(1);
|