Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Are ArrayList and ArrayList<Object> two different classes?

If so, what is the difference between the two? Are there actually two separate class definitions in the java library? One for the old ArrayList and one for the new generic one? This is purely a question from curiosity.

like image 268
Tim Avatar asked Dec 09 '22 02:12

Tim


2 Answers

There is just one class ArrayList, but it supports generics, which means that you can annotate it with a type. However, that is optional (mostly for backwards compatibility), so you can also continue to use the raw type (but that is discouraged).

Note that Java generics only happen for the compiler, at runtime the ArrayList instance itself has no idea what generic type you assigned to it. This means that it works exactly the same way internally if you annotate it or not.

Unlike arrays, there are no new separate classes for generic collections. So while there is actually a different class for Integer[] than for String[] (or for Integer[][]), the class for ArrayList<String> is the same as for ArrayList<Integer> (and ArrayList<?> and ArrayList and ArrayList<List<Integer>>).

And also unlike arrays, there is nothing special in generics for use by collections (although that remains their most popular application). The same mechanism can be used for completely different things, for example a Callable.

like image 145
Thilo Avatar answered Dec 14 '22 23:12

Thilo


No, they're the same class, in that there's only one class file. Existing API classes were "generified" in such a way that old code could continue to be compiled with no change, and interoperate nicely with new code which used the new features.

like image 45
Ernest Friedman-Hill Avatar answered Dec 14 '22 22:12

Ernest Friedman-Hill