我正在学习类型擦除。我知道在类型擦除之后,泛型类型要么变成object,要么变成上限。但是,如果泛型类型成为对象,类型安全性不会丢失吗?
例如,以下示例中的:-
List<String> a = new ArrayList<String>();
a.add(10) // I can't do this, but after type erasure the generic type becomes object so where is
the check for the type?任何帮助我们都将不胜感激
发布于 2021-06-03 20:49:06
检查在编译时进行。如果编译程序示例,则会得到以下错误:
error: no suitable method found for add(int)
a.add(10);
^
method Collection.add(String) is not applicable
(argument mismatch; int cannot be converted to String)
method List.add(String) is not applicable
(argument mismatch; int cannot be converted to String)这表明List不允许您添加整数,因为它不是字符串并且不能转换为字符串。
https://stackoverflow.com/questions/67821707
复制相似问题