Java獲取隨機數、隨機字符串(五種方法)

目錄

一、Math.random()

二、Random

三、ThreadLocalRandom

四、System.currentTimeMillis()

五、UUID


一、Math.random()

Math.random():獲取double類型的小數範圍 [0.0,1.0)

  • 線程安全
  • 最常用

獲取[max,min]之間的隨機數公式:

(int)(Math.random()*(max - min - 1) + min)

假設max爲3,min爲1
當Math.random()取得最小隨機數時,結果爲0*(3 - 1 + 1) + 1 = 1
當Math.random()取得最大隨機數時,結果 > 1*(3 - 1 + 1) + 1 ≈ 3.99999,進行強制類型轉換之後得3

public static void getRandomByMathRandom(){
        int max = 3;
        int min = 1;
        int temp = (int)(Math.random()*(max - min + 1) + min);
        System.out.println(temp);
    }

二、Random

Random類中的nextInt():獲取[0, max)之間的隨機整數

  • 線程安全
  • 非加密安全(加密安全推薦使用:SecureRandom)
new Random().nextInt(max);

注:類似的可以調用nextLong(),nextDouble(),nextFloat()……

public static void getRandomByRandom(){
        int max = 3;
        int temp = new Random().nextInt(max);
        System.out.println(temp);
    }

三、ThreadLocalRandom

ThreadLocalRandom:與當前線程隔離的隨機數生成器。(從jdk1.7版本開始)

  • 多線程時推薦使用

獲取[min,max)之間的隨機數代碼

int temp = ThreadLocalRandom.current().nextInt(min, max);

注:類似的可以調用nextLong(),nextDouble()……

public static void getRandomByThreadLocalRandom(){
        int max = 5;
        int min = 1;
        int temp = ThreadLocalRandom.current().nextInt(min, max);
        System.out.println(temp);
    }

四、System.currentTimeMillis()

System.currentTimeMillis():返回當前時間

  • 其實沒什麼優點,不推薦使用

獲得[min,max)之間的隨機整數

int temp = (int)(System.currentTimeMillis() % (max - min) + min);
public static void getRandomByCurrentTimeMillis(){
        int max = 5;
        int min = 2;
        long temp = System.currentTimeMillis();
        int random = (int)(temp % (max - min) + min);
        System.out.println(random);
    }

五、UUID

UUID:表示一個可變的通用唯一標識符

  • 加密安全

生成隨機字符串:

String temp = UUID.randomUUID().toString();
public static void getRandomByUUID(){
        String temp = UUID.randomUUID().toString();
        System.out.println(temp);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章