int
特定の範囲内でランダムな値を生成するにはどうすればよいですか?
次のメソッドには整数オーバーフローに関連するバグがあります。
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
ベストアンサー1
Java 1.7 以降では、これを実行するための標準的な方法 (範囲[min, max]内の基本的な非暗号的に安全なランダムな整数を生成する) は次のとおりです。
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
見る関連するJavaDocこのアプローチの利点は、明示的に初期化する必要がないことです。java.util.ランダムたとえば、不適切に使用すると混乱やエラーの原因となる可能性があります。
しかし、逆にスレッドローカルランダムシード値を明示的に設定する方法がないため、テストやゲーム状態の保存など、シード値が有用な状況で結果を再現することが難しい場合があります。
Java 17以降、標準ライブラリの疑似乱数生成クラスは、ランダムジェネレータインターフェース。詳細については、リンクされたJavaDocを参照してください。たとえば、暗号的に強力な乱数ジェネレータが必要な場合は、セキュアランダムクラスを使用できます。
Java 1.7 より前では、これを行う標準的な方法は次のとおりです。
import java.util.Random;
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {
// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance. Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will get not very good / not very random results.
Random rand;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
見る関連するJavaDoc実際には、java.util.ランダムクラスはしばしばjava.lang.Math.random()。
特に、標準ライブラリ内にタスクを実行するための簡単な API がある場合は、ランダム整数生成ホイールを再発明する必要はありません。