Domanda

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?

È stato utile?

Soluzione

ArrayList<String> str

This is just variable declared

ArrayList<String> str = new ArrayList<String>();

It is initialization of str variable with default size 10.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top