我想创建一个跨多个类使用的随机int值。每次我创建这些类的一组新实例时,我都想要一个新的随机int值用于所有这些。随机值应该是相同的。
简而言之,我想要创建一个随机索引,并在多个一起工作以生成数据的类中使用。
这个随机值是应该在堆栈顶部生成的,并且在每个一起工作的类中静态调用吗?
答案 0 :(得分:6)
只需创建一个包含随机值字段的类。提供一个getter方法来访问它。然后,与每个新的类批次共享此类的新实例。
E.g。
private static final Random random = new Random();
private final int randomValue = random.nextInt();
...
public int getRandomValue() {
return randomValue;
}
这样,每组的随机数相同,但每组不同。
答案 1 :(得分:1)
这样的事情
static class Utility {
private static final int variable = (int)Math.round(1000*Math.random());
public static int getVariable() {
return variable;
}
}
它的工作方式与Math.PI等相同。 e.g。
System.out.println(Utility.getVariable());
答案 2 :(得分:1)
只需将其传递给构造函数中的相关对象:
class Main {
public static void main() {
Random rnd = new Random();
for (...) {
int index = rnd.nextInt();
// one set of related instances
Foo f = new Foo(index);
Bar b = new Bar(index);
}
}
}
class Foo {
int randomIndex;
public Foo(int randomIndex) {
this.randomIndex = randomIndex;
// etc.
}
}
class Bar { ... }
如果您希望某个类的实例之间的值不同(无论它们是否同时存在),不要使其静态。
答案 3 :(得分:1)
首先通过使用一个专用类来重新理解你所谈论的“群组”的概念,该类将保存与每个群组相关的元数据:
class Group
{
private int index = -1;
public Group(int index)
{
this.index = index;
}
public int getIndex()
{
return index;
}
}
然后为每个类分配其group-info数据。
如果在每个对象的instanciation之前知道索引,请使用构造函数。 请注意,工厂模式可以帮助您封装实例化过程(如果它很复杂。)
如果您知道后者并仍然可以访问实例,请使用专用方法:
public void assignToGroup(Group group)
如果您无法再访问实例,可以使用一些简单的反转:每个实例都会询问其组:
getMyGroup(this)
到外部方法:
public Group getMyGroup(MyClass instance)
{
// ... some complex logic to determine the right group based on the instance state ...
}