随机返回真或假

2022-01-19 00:00:00 random boolean java

我需要创建一个 Java 方法来随机返回 truefalse.我该怎么做?

I need to create a Java method to return true or false randomly. How can I do this?

推荐答案

java.util.Random已经有这个功能了:

public boolean getRandomBoolean() {
    Random random = new Random();
    return random.nextBoolean();
}

但是,每次需要随机布尔值时总是创建一个新的 Random 实例效率不高.相反,在您的类中创建一个需要随机布尔值的 Random 类型的属性,然后为每个新的随机布尔值使用该实例:

However, it's not efficient to always create a new Random instance each time you need a random boolean. Instead, create a attribute of type Random in your class that needs the random boolean, then use that instance for each new random booleans:

public class YourClass {

    /* Oher stuff here */

    private Random random;

    public YourClass() {
        // ...
        random = new Random();
    }

    public boolean getRandomBoolean() {
        return random.nextBoolean();
    }

    /* More stuff here */

}

相关文章