簡體   English   中英

如何從Java中的多個finals字符串中隨機選擇一個字符串?

[英]How to randomly pick a string from multiple finals strings in Java?

正如問題所述,我在這樣的最終課程中擁有多個總決賽字符串:

public final class MyStrings {

    public static final String stringOne = "this is string one";
    public static final String stringTwo = "this is string two";
    public static final String stringThree = "this is string three";
    public static final String stringFour = "this is string four";
    public static final String stringFive = "this is string five";

}

我知道將它們放在列表或數組中會更容易,但是我想避免在運行時填充這些結構。 可能嗎? 從該類中隨機選擇字符串的最簡單方法是什么? 謝謝。

您的String似乎非常相關,因為您有一個用例,需要從其中隨機選擇一個。 因此,無論如何(從語義的角度來看)它們都應該以數組的形式收集。

當前的多個字段不會比“運行時填充”更多:

public final class MyStrings {

    public static final String[] strings = {
        "this is string one",
        "this is string two",
        "this is string three",
        "this is string four",
        "this is string five"
    };
}

然后,您可以通過以下方式隨機選擇一個String

Random random = new Random();
String randomString = strings[random.nextInt(strings.length)]);
String[] mystring = {
    "this is string one",
    "this is string two",
    "this is string three",
    "this is string four",
    "this is string five"
};

int idx = new Random().nextInt(mystring.length);
String random = (mystring [idx]);

將這些字符串放入最終數組中,並生成一個從0到array.length-1的隨機數

您不必擔心用這些字符串填充數組的性能成本,因為這是迄今為止最合理的方法!

將每個字符串加載到數組中,並生成一個從0(數組索引從0開始,請注意!)到數組末尾的隨機數-1(由於數組從0開始,因此必須從數組長度減去1。數組)。 然后使用隨機數作為選擇字符串的索引。

使用一個枚舉:

public enum MyStrings {
    ONE("This is string one"),
    ETCETERA("Other strings");

    private final String label;

    private MyStrings(String label) {
        this.label = label;
    }
}

然后

String randomLabel = MyStrings.values()[random.nextInt(MyStrings.values().length].label;

這有2個優點:

  1. 它允許您延遲將枚舉值轉換為String (可能使其余代碼中的類型簽名更有用)。
  2. 它使您無法用其他字符串替換數組值。

性能警告:每次調用MyStrings.values()時,在內存中創建一個新的(短)數組都會對性能產生輕微影響。 這不太可能產生任何可衡量的影響。 在不太可能的情況下,您確實測量出這是一個瓶頸(然后,您可能也想使用自定義隨機函數),您可以優化它,也可以選擇其他結構。

使用反射API將MyStrings.class中的所有public static final String字段獲取到稱為字符串的數組中

然后隨機生成一個從0到numStrings-1的整數n

隨機字符串是字符串[n]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM