5

Possible Duplicate:
C# vs Java generics

Java use Type erasure while C# keep type information at runtime, what are the practical difference in the behaviors of the language from this design?

Community
  • 1
  • 1
Ryan
  • 10,041
  • 27
  • 91
  • 156

3 Answers3

5

There are a lot of issues with type erasure. It brings back bad memories. I haven't used Java since 1.6, so this may be out of date, but some things I remember:

  1. You can't create a new T (or do anything that requires knowing what type T actually is)
  2. Generic lists can't create an array of T
  3. You can't use int, float, etc in generics with Java
    1. This has performance and memory implications because you always have to use the heap versions (Integer, etc)
  4. You can't implement a generic interface with two different Ts, e.g. class c implements IComparable<MyClass>, IComparable<MyOtherClass> is impossible.
    1. More practically, you can't overload methods with different generic types, e.g. by taking in List<T1>, List<T2>, and so on. For example, Java -- How to deal with type erasure in constructors?
  5. Everything is done by casting and boxing
Community
  • 1
  • 1
Mark Sowul
  • 10,244
  • 1
  • 45
  • 51
2

Here's an example of something that's possible only if the type information is kept at runtime:

public string DoSomething<T>()
{
    return typeof(T).Name;
}

The closest you could get in Java is something like:

public <T> string DoSomething(Class<T> theClass)
{
    return theClass.getName();
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

Something that happens in Java due to type erasure is the creation of synthetic methods called "Bridge methods".

This usually happens when Java tries to compile a class or interface that extends a parameterized class, or implements a parameterized interface. In this case the Java compiler may need to create a synthetic method (bridge method) as part of the type-erasure process, which appears in the stack trace.

The compiler does this to preserve polymorphism of generic types after the type erasure process.

Java's documentation has an example.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295