I am having some trouble with this for
loop. I am not sure if I have correctly set up this method.
Here is what it is asking me to do
Iterate over all the elements in the subscribers array. You should use the easier version of
the for
loop to do this. Inside the loop: If the element is not equal to null
, then call the
notify
method on that subscriber. When you call that method you need to give it a
Message
argument: use the same Message
that was given to this method.
Note that here you are inside the notify
method, and you're calling the notify
method
again. However, this is not recursion because the notify method you're calling is on a
completely different ISubscriber
instance.
package message;
public class Broadcaster implements IPublisher, ISubscriber {
private Object [] members;
private int i = 0;
Broadcaster(int a) {
a = 4;
Object[] array = new Object[a];
members = array;
}
@Override
public void subscribe(ISubscriber subscriber) {
members[i] = subscriber;
i++;
}
@Override
public void unsubscribe(ISubscriber subscriber) {
}
@Override
public void notify(Message msg) {
}
}
Usually you don't use an Array for this but something dynamic. e.g. a LinkedList
If you are forced to use an array you get something like this:
The downside of using an array is that you either can only store a certain number of elements or have to change the size of the array as soon as you run out of free slots.
As you can see it is also a bit harder to avoid that subscribers are added twice to the array. It requires an addition loop just to check this while the LinkedList offers a convenient method for this check.
And last but not least: While it is possible to have a
notify()
and anotify(Message msg)
method that do entirely different things this is not good practice as it can easily lead to mixing up the functions.