Forgive me if this has an answer somewhere; I didn't really know what to search for... Also, my terminology may be off (declare, instantiate, etc) as I am still learning Java and OOP.
I was reading the textbook: Data Structures and Abstractions, 3rd Ed by Frank Carrano (Chaper 20: Dictionary Implementation), and I came across a pretty standard looking class containing a private inner class. But there is something about the methodology I don't quite get.
I am having a difficult time understanding why you would declare an object (or array of objects) as a field in the outer class, then in the constructor, instantiate a temp object and initialize the field as the temp object rather than just instantiating the attribute itself in the constructor.
EDIT: I added the type parameter back into the code... K & V are used for key and value in this case since we are working with dictionaries. I don't know if that is important to the question or not...
I have rewritten the code in question here, renaming classes and such so they aren't so localized:
public class OuterClass<K, V> implements SomeInterface<K, V>
{
private InnerClass<K, V>[] foo; // Declare array of inner class object
private final static int CAPACITY = 10; // Initial Array Capacity
// Outer Class Constructor
public OuterClass()
{
InnerClass<K, V>[] tempFoo = (InnerClass<K, V>[])new InnerClass[CAPACITY];
foo = tempFoo;
}
// ...
private class InnerClass<S, T>
{
// Inner Class Constructor
private InnerClass()
{
// ...
}
// ...
}
}
As mentioned, I tried to get rid of any specific details in the code, as I don't think they are relevant to the question. Is there any reason why you wouldn't just do this in the outer class constructor:
foo = (InnerClass[])new InnerClass[CAPACITY];
instead of:
InnerClass[] tempFoo = (InnerClass[])new InnerClass[CAPACITY];
foo = tempFoo;
This is enough:
foo = new InnerClass[CAPACITY];
UPDATE after generics edit of OP:
With generic type parameters the situation changes because you use a raw type on the right side. In this case casting is necessary, and you get a compiler warning because the cast cannot be type-safe. So we then have:
foo = (InnerClass<K, V>[]) new InnerClass[CAPACITY];