Reputation: 93
I was reading online and I saw a declaration for an ArrayList
as
ArrayList[] graph = new ArrayList[numCourses];
Traditionally, I thought that ArrayList
s 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
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
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 ArrayList
s (with no type) - those are whole different objects.
If you want a collection of parametrized List
s, array is not the way to go. Better use nested lists: List<List<type>>
.
Upvotes: 1
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