0

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.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
Jeffrey
  • 83
  • 5

3 Answers3

4

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

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>();
Community
  • 1
  • 1
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
1

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>>.

Andronicus
  • 25,419
  • 17
  • 47
  • 88