[ABE.pm] Type erasure in Java

Walt Mankowski waltman at pobox.com
Thu Oct 26 09:42:03 PDT 2017


At dinner last night we were talking about type erasure with generics
in Java. I couldn't remember the specific example that illustrated a
problem it causes. I just found it and thought I'd share it here.

I first encountered type erasure when teaching Collections in a Java
class at Drexel. Collections are classes that implement data
structures like linked lists, sets, and maps. Collection classes all
use generics, so you could for example say

  List<Integer> list_of_ints;
  List<String> list_of_strings;

Syntactically they look just like similar classes in the C++ Standard
Template Library, but their implementation is quite different.
Java'sCollection classes all inherit from a root class that provides a
toArray() method to return the underlying data structure as a normal
array. In fact, it provides 2 overloaded toArray() methods:

  Object[] toArray();
  <T> T[]  toArray(T[] a);

This seemed odd to me. Why can't there by a single toArray() method
that does something like this?

  T[] a = new T[t.size()];
  // copy underlying data structure to a
  return a;

It turns out that doesn't work because Java throws away the datatype
of T after compilation. At runtime everything is class Object. So
instead, you've got to do something like this:

  String[] array_of_strings = x.toArray(new String[0]);

It only uses the array as a hack to pass in the type at runtime!

Walt


More information about the ABE-pm mailing list