ArrayList<String> str
This is just variable declared
ArrayList<String> str = new ArrayList<String>();
It is initialization of str variable with default size 10.
문제
Sometimes I see ArrayLists declared like
ArrayList<String> str;
while other times I see it done like
ArrayList<String> str = new ArrayList<String>();
Is there any difference between the two? Or are the same and is one just preferable to use over the other?
해결책
ArrayList<String> str
This is just variable declared
ArrayList<String> str = new ArrayList<String>();
It is initialization of str variable with default size 10.
다른 팁
In the first one there is just a declaration of the object while in the second one you do initialization too.
There is no constraint on the place in which you should initialize an object except that it should happen before trying to access the object.
The first snippet is just declaring the ArrayList
(and it's null
at this point), the second one is declaring and instantiating it. There isn't any significant difference, IMHO the second version is more useful, so you won't risk forgetting to instantiate the object.