Java Array

本文最后更新于 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()};

返回数组

  • Java可以直接返回数组

多维数组

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));
// output: [1, 1, 1, 1]

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));

// [2, 5, 6, 7, 7, 8, 9, 10, 34]

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));
// true
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));
// true

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));
// [8, 9, 7, 721]

int[] org = new int[]{8,9,7,721};
int[] des = Arrays.copyOf(org,3);
System.out.println(Arrays.toString(des));
// [8,9,7]

int[] org = new int[]{8,9,7,721};
int[] des = Arrays.copyOf(org,9);
System.out.println(Arrays.toString(des));
// [8, 9, 7, 721, 0, 0, 0, 0, 0]

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));
// [1, 2, 3]
//[[1, 2], [3, 4], [5, 6]]

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));
// [1, 3, 4, 5, 5, 6, 7, 8, 34, 54, 67, 76, 78, 90]
// 12

asList()

常用于声明对象组成的列表

1
2
3
4
5
6
7
8
List<Integer> l1 = Arrays.asList(1,2,3);
System.out.println(l1);
// [1, 2, 3]
List<Student> l2 = Arrays.asList(
new Student("xiaoming",21),
new Student("xiaomei",19));
System.out.println(l2);
// [xiaoming 21, xiaomei 19]

setAll()

使用提供的生成器函数设置指定数组的所有元素以计算每个元素

1
2
3
Set<Integer>[] s = new HashSet[maxlen];
Arrays.setAll(s, i ->new HashSet<Integer>());
s[0].add(1);

Java Array
https://meteor041.git.io/2024/09/11/Java-Array/
作者
meteor041
发布于
2024年9月11日
许可协议