Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics understanding [duplicate]

Tags:

java

generics

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

like image 542
Patison Avatar asked Feb 23 '26 17:02

Patison


1 Answers

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.

like image 92
Sergey Kalinichenko Avatar answered Feb 25 '26 06:02

Sergey Kalinichenko