How do you use type erasure with a simple code example?

Type erasure is a mechanism in Java that allows generic types to be implemented without retaining the information about the type parameters at runtime. This means that the generic type information is erased or not available after compilation. Here’s a simple code example to demonstrate type erasure in Java:

// A simple generic class public class Box { private T item; public void setItem(T item) { this.item = item; } public T getItem() { return item; } } // Example of using the generic class public class Main { public static void main(String[] args) { Box stringBox = new Box<>(); stringBox.setItem("Hello, World!"); System.out.println(stringBox.getItem()); Box integerBox = new Box<>(); integerBox.setItem(123); System.out.println(integerBox.getItem()); } }

Type Erasure Java Generics Generic Types Runtime Type Information