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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top