Reputation: 15
I'm creating a class that has an ArrayList, so when I call the constructor it initializes that array:
public class ElementsList<E>
{
private ArrayList<E> list;
public ElementsList()
{
list = new ArrayList<E>;
}
}
I dont understand why when you create the constructor, you don't really have to mention the fact that this class is going to keep certain elements. What I mean is that you don't have to do this:
public ElementsList<E>{
list = new ArrayList<E>;
}
LONG STORY SHORT: Why the name of the class is ElementsList<E>
, and the constructor does NOT have the <E>
part?
Upvotes: 0
Views: 74
Reputation: 1179
Your list isn't final. If it was, then you would have been able to force the initialization. If you use this list in your code though, you will get warnings by the IDE that this parameter may have not been initialized. Also you are using the new keyword. You must specify () even though you don' need any parameters in the constructor. This is the way the new keyword works to create single instances in the contructors. You don't need this for Arrays for example. If you don't want to use new you have several options. Look into this page. Design patterns. For this example I think what you are looking for is a Factory Pattern. And, if you look at your class declaration you are specifying a generic type E. The class already knows what type E is. If you would make a contructor with another type then that wouldn't make sense. That is why specifying it in the declaration of the class it's enough. E will be of a known type once your element is created. For exemple if I want an Element that deals with type Integer:
ElementsList<Integer> e = new ElementsList<>();
Now I know that I have list inside with Integer elements.
Upvotes: 0
Reputation: 21630
In the constructor declaration you do not need to mention the element type E
again since you already did that at the class declaration level.
I.e. you already declared your class
public class ElementsList<E> {
so the identifier E
already denotes your element type.
Writing your constructor as
public <E> ElementsList() {...}
would effectively denote another type that is independent of the element type of your class.
Upvotes: 5