How can I reset all object values with only one method call?
java
Solution
First option: Memorize each instance of `Counter`.
Collect each instance of `Counter` in 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:
- Using weak references will avoid the issue that the `Counter` objects 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.
- The collection of every instance can be achieved by declaring the `Counter` constructor `private` and allowing only construction through a `static` member 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 the `Counter` constructor register `this` with the static collection.
Second option: Generation counter
Keep a `static` generation counter of type `long`, and also a copy of this counter in each instance. When resetting all counters, just increase the `static` generation counter. The `getNumber()` method will then check the `static` generation counter against its own copy and reset the counter if the `static` generation counter has changed.
(I don't really know the "official" name for this trick. How to zero out array in O(1)?)
Problem
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() { } } ```