Basically, I want to create Counter objects, all they have to do is hold number values. And in my resetCounters method, I would like to reset each object’s values. This is probably very easy, but I’m a newb.
public class Counter
{
Random number = new Random();
Counter()
{
Random number = new Random();
}
public Random getNumber()
{
return number;
}
public void setNumber(Random number)
{
this.number = number;
}
public static void main(String[] args)
{
Counter counter1 = new Counter();
Counter counter2 = new Counter();
Counter counter3 = new Counter();
Counter counter4 = new Counter();
Counter counter5 = new Counter();
}
public static void resetCounters()
{
}
}
First option: Memorize each instance of
Counter.Collect each instance of
Counterin some static collection.To reset all, simply iterate over all items in the collection.
But strong references are too strong for this — make sure it’s a collection of weak references.
Remarks:
Counterobjects exist indefinitely only because of their reference from within the static collection. Objects that are referred to only by weak references are eventually collected by the garbage collector.Counterconstructorprivateand allowing only construction through astaticmember function which will also do the registration. (Or use some other incarnation of the Factory pattern.) I believe a factory is the way to go here, since each construction of an object has to carry out also a side effect. But perhaps it will make do to have theCounterconstructor registerthiswith the static collection.Second option: Generation counter
Keep a
staticgeneration counter of typelong, and also a copy of this counter in each instance. When resetting all counters, just increase thestaticgeneration counter. ThegetNumber()method will then check thestaticgeneration counter against its own copy and reset the counter if thestaticgeneration counter has changed.(I don’t really know the “official” name for this trick. How to zero out array in O(1)?)