Home > database >  What makes Arraylist a generic type and arrays not in Java?
What makes Arraylist a generic type and arrays not in Java?

Time:10-20

Very confused about the difference between Arraylists and Arrays when it comes to classifying them as generic. We aren't really talking about generic programming in my course and when they explained the difference it was mostly about how one can grow and the other can't. That doesn't really seem to be what I think the difference really is when we say a class is generic. A google search left me even more confused.

What I saw was "A generic type is a generic class or interface that is parameterized over types." But don't Java’s arrays allow parameterized types? But just written in a different form? e.g. the array type String[] is analogous to the arraylists type Arraylist<String> to me. Would really appreciate a simple(high level) explanation to this.

CodePudding user response:

What makes ArrayList a generic type and arrays not in Java?

ArrayList is a class, and has a declaration that looks like this (you can find this here):

public class ArrayList<E> // ...

Note the "<E>". This declares a type parameter called E, and that is what makes ArrayList generic. You can also find this in the API reference of ArrayList.

Arrays, on the other hand, are not classes or interfaces. They are not generic because only classes and interfaces can be generic.

JLS §4.3:

There are four kinds of reference types: class types (§8.1), interface types (§9.1), type variables (§4.4), and array types (§10.1).

JLS §8.1.2:

A class is generic if it declares one or more type variables (§4.4).

JLS §9.1.2:

An interface is generic if it declares one or more type variables (§4.4).

Historical side note: generics are added to Java much later than arrays, which has been in Java since the very beginning, so there's also that.

  • Related