昨天和一个朋友聊天谈到他的面试经历,其中提到一个题目是用最熟悉的语言写一个程序产生15个10到100的整数,他特别提到他用Java写了一些循环并每次重新用
当前时间的long值做种子,当时我就很奇怪,但是他说Random有问题,每次产生的随机数都是一样的。回想了一下,他可能是遇到了我曾经遇到的那个问
题,在使用Random的时候要把产生的Ramdom实例保存起来,不能每次用的时候都重新new一个。具体代码如下:
范例代码如下:
public class RandomTest {
  private static Random random = new Random();

  public static void main(String[] args) {
    for (int i = 0; i < 15; i++) {
      System.out.println((random.nextInt(90) + 10));
    }
  }

}

典型的误用代码如下:
public class RandomTest {
  public static void main(String[] args) {
    for (int i = 0; i < 15; i++) {
      Random random = new Random();
      System.out.println((random.nextInt(90) + 10));
    }
  }

}

2005.11.18更新:
对于这个里面的误用代码JDK1.5确实修正了,但是修正的方法是修改了new Random(),1.5以前实际上是

public Random()
Creates a new random number generator. Its seed is initialized to a value
based on the current time:

 public Random() { this(System.currentTimeMillis()); }

Two
Random objects created within the same millisecond will have the same sequence
of random numbers.

而在1.5中是:

public Random()
Creates a new random number generator. This constructor sets the seed
of the random number generator to a value very likely to be distinct
from any other invocation of this constructor.

所以实际上1.5中并没有彻底解决这个问题,根据同样是他的文档:
If two
instances of Random are created with the same seed, and the same
sequence of method calls is made for each, they will generate and
return identical sequences of numbers.
那么典型的误用代码就变成了:
public class RandomTest {
  public static void main(String[] args) {
    for (int i = 0; i < 15; i++) {
      Random random = new Random(100000);
      System.out.println((random.nextInt(90) + 10));
    }
  }

}

(Visited 28 times, 1 visits today)