What’s the difference between these two methods of initializing the observers ArrayList. Or any other type for that matter. Is one faster than the other? Or am I missing some other benefit here.
class Publisher implements Observerable
{
private ArrayList observers = new ArrayList();
}
class Publisher implements Observerable
{
private ArrayList observers;
public Publisher()
{
observers = new ArrayList();
}
}
They’re equivalent. In fact, if you compile the two you’ll see that they generate exactly the same byte code:
Given that they’re the same code, there clearly can’t be any speed difference 🙂
Note that in C# they’re not quite equivalent – in C# the initializer for
observerswould run before the base constructor call; in Java they really are the same.Which you use is a matter of taste. If you have several different constructors which all initialize a variable in the same way it would make sense to use the first form. On the other hand, it’s generally a good idea if you have several constructors to try to make most of them call one “core” constructor which does the actual work.