avatar

目录
Java 常用代码段

序列化类:

java
1
2
import java.io.Serializable;
public class User implements Serializable{}

JSONObject 中获取所有的key

java
1
2
3
4
5
6
7
8
9
10
11
12
13


net.sf.json-lib
json-lib
2.4
jdk15


Iterator keys = jsonObject.keys();
while(keys.hasNext()){
String key = keys.next().toString();
System.out.println("key:"+key);
};

UUID

java
1
UUID uuid = UUID.randomUUID();  // java uuid

java端随机数

java
1
int random = new Random().nextInt(800);

获得系统时间

java
1
long timestamp = System.currentTimeMillis();

测时间-性能–代码执行时间

java
1
2
3
4
long begin_time = System.currentTimeMillis();
long end_time = System.currentTimeMillis();
long time = end_time- begin_time ;
String result = "用时:"+(time > 60000 ? (time / 60000) + "分钟" : time > 1000 ? (time / 1000) + "秒" : time + "毫秒");

随机数

  • 获得一组不重复的随机数组

    java
    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内不重复的数组

    java
    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;
    }
  • 打乱有序数组

    java
    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;
    }
文章作者: 颜不喜
文章链接: https://www.muycode.cn/article/java20200324.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 颜不喜
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论