Java 常用代码段
序列化类:
1 | import java.io.Serializable; |
JSONObject 中获取所有的 key
1 | <!--JSONObject--> |
UUID
1 | UUID uuid = UUID.randomUUID(); // java uuid |
java 端随机数
1 | int random = new Random().nextInt(800); |
获得系统时间
1 | long timestamp = System.currentTimeMillis(); |
测时间 - 性能–代码执行时间
1 | long begin_time = System.currentTimeMillis(); |
随机数
获得一组不重复的随机数组
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/**
* 获得一组不重复的随机数组
*
* @param length
* @return
*/
public int[] getRandom(int length) {
int[] numbers = new int[length];
for (int i = 0; i < numbers.length; i++) {
int num = 0;
while (true) {
boolean tag = false;
num = (int) (Math.floor(Math.random() * length)) + 1;
for (int j = 0; j < numbers.length; j++) {
if (numbers[j] == num) {
tag = true;
break;
}
}
if (!tag) {
break;
}
}
numbers[i] = num;
}
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] - 1;
}
return numbers;
}根据传递过来的长度,随机分配 60S 内不重复的数组
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/**
* 根据传递过来的长度,随机分配 60S 内不重复的数组
*
* @param length
* @return
*/
public int[] randomNextMinute(int length) {
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
int ran;
while (true) {
ran = (int) (Math.random() * 60);
if (ran > 60) {
ran = ran - 60;
}
boolean tag = false;
for (int j = 0; j < arr.length; j++) {
if (arr[j] == ran) {
tag = true;
}
}
if (!tag) {
break;
}
}
arr[i] = ran;
}
return arr;
}打乱有序数组
1
2
3
4
5
6
7
8// 打乱有序数组
Random random = new Random();
for (int i = allMoney.length - 1; i >= 0; i--) {
index = random.nextInt(allMoney.length);
int temp = allMoney[i];
allMoney[i] = allMoney[index];
allMoney[index] = temp;
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 颜不喜!