0

As the official tutorial about generics type erasure, and this statement is so confusing me. When the type cast inserting might occur exactly? I tried with some simple usages of generics and using javap -c a.class to check the bytecode but it seems no typecasting inserted as I expected.

The so-called duplicated is more about the bridge method using a type cast to ensure there is proper polymorphism while I am wondering what the second statement means exactly.

Insert type casts if necessary to preserve type safety.

Any example could be provided to demonstrate it?

Hearen
  • 7,420
  • 4
  • 53
  • 63
  • Can you please post a.java code – Amit Bera Mar 10 '19 at 04:49
  • 1
    Possible duplicate of [Java Type Erasure: Rules of cast insertion?](https://stackoverflow.com/questions/29587502/java-type-erasure-rules-of-cast-insertion) – Tom Mar 10 '19 at 05:00

1 Answers1

1

In the end, I think Jon Skeet's answer cleared out the confusion.

when generics are used, they're converted into compile-time checks and execution-time casts.

When we try to compile a.java and decompile the a.class, we will see the magic (compiler helps auto-insert type cast).

    List<String> list = new ArrayList<>();
    list.add("hell");
    out.println(list.get(0));

After being decompiled:

    ArrayList var3 = new ArrayList();
    var3.add("hell");
    System.out.println((String)var3.get(0));

Using Legacy Code in Generic Code from the official generic tutorial:

... whenever the resulting code isn't type-correct, a cast to the appropriate type is inserted...

Hearen
  • 7,420
  • 4
  • 53
  • 63