Could you please explain to me what happens here and why it works without errors.
List list = new ArrayList<String>();
list.add(1);
I'm sorry, if there already were similar questions, I failed to properly formulate the question so can't google it
What happens here exposes the weakness of type erasure, the mechanism behind Java generics. The implementation of ArrayList does not change when you change its generic type parameter: it's always java.lang.Object behind the scene.
Since you did not give a type parameter to the interface when declaring your list, compiler allows you to add objects of any type, not only Strings. In particular, int gets autoboxed into java.lang.Integer, so the value of 1 can be added to your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With