Jeffrey
Jeffrey

Reputation: 93

Difference between ArrayList declarations

I was reading online and I saw a declaration for an ArrayList as

ArrayList[] graph = new ArrayList[numCourses];

Traditionally, I thought that ArrayLists were always declared as

ArrayList<type> graph = new ArrayList<type>();

What's the difference between these two? The rest of the code seemed to utilize the same functions from the ArrayList class, but with specific indices.

Upvotes: 0

Views: 151

Answers (3)

ernest_k
ernest_k

Reputation: 45339

ArrayList[] declares an array of ArrayList objects. graph is then initialized with an array of length numCourses.

While ArrayList[] uses the raw type ArrayList, ArrayList<type> graph uses the generic type ArrayList<T> and passes type as the type argument.

These two are not interchangeable. An array cannot be used instead of its component type. ArrayList[] is probably being used to circumvent the limitation that prevents the instantiation of arrays of generic types.

Upvotes: 4

Andronicus
Andronicus

Reputation: 26076

With brackets ([]) an array is created, whereas with "beaks" (<>) parameter type is passed.

Your second line creates an ArrayList of type type, whereas the first line creates an array of raw ArrayLists (with no type) - those are whole different objects.

If you want a collection of parametrized Lists, array is not the way to go. Better use nested lists: List<List<type>>.

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15906

From Oracle: Cannot Create Arrays of Parameterized Types

You cannot create arrays of parameterized types. For example, the following code does not compile:

List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-time error

So yeah you are right only correct way to declare List or collection in general is like below:

ArrayList<type> graph = new ArrayList<type>();

Upvotes: 1

Related Questions