开发者

Avoid new Random for each instance schenanigans

Trying to get this code off the ground:


    Random random = new Random();

public Particle(int mouseInputX, int mouseInputY, int[] RGBBounds){
    this(mouseInputX, mouseInputY, 6, 12+ random.nextInt(10),RGBBounds);

But netbeans espouses that I can't reference random before the superclass constructor has been called. So I tried this:


        this(mouseInputX, mouseInputY, 6, 12+ new Random().ne开发者_StackOverflowxtInt(),RGBBounds);

Which works, but I don't want to create a new Random object for each particle object made (performance is already an issue). How to proceed?


Either way you are creating a new Random() object for each instance.

If you don't want to, you can make it static. But consider thread-safety. Take a look at this article by Jon Skeet (plus the comments below)


You can make it static and provide a static synchronized method to access it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜