java - 通配符和原始类型转换之间有什么区别?

标签 java generics casting

以下有什么区别?

List <?> list = (List<?>) var;
List <String> list = (List) var;

最佳答案

本质上,区别在于一种使您的代码类型安全,一种使其类型不安全。

如果转换为原始类型,例如 (List)var ,你基本上放弃了泛型提供的安全性。 var可能是 List<Integer> , 现在你已经转换了它,你可以将它分配给 List<String>没有编译器提示。您甚至可以从中获取字符串(应该是 List<Integer> )而编译器不会提示(但这会在运行时抛出异常)。所以转换为原始类型就像对编译器说:

I don't know exactly what type of list this will be right now, but I will do at runtime. I can hold all this type information of all these variables in my head all at once, so you don't need to worry about it! I'll handle types on my own.

...如果编译器已经可以为您完成,那么这不是明智之举。人类往往会犯错误。

转换为(有界的)通配符就像对编译器说:

I don't know exactly what type of list this will be right now, but I will do at runtime. I can't hold all this type information of all these variables in my head all at once, so you have to give me an error whenever what I am doing might not succeed all the time, ok?

在这种情况下,编译器知道您不知道泛型参数,因此不允许您做某些事情,例如添加 StringList<?> ,因为 ?可能是 Integer .您仍然可以获得 Object出自 List<?>不过,因为无论?也就是说,它必须是 Object 的子类.

关于java - 通配符和原始类型转换之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57350819/

相关文章:

go - 将 func 类型转换为其他 func 类型

c# - 为什么转换和转换操作在语法上无法区分?

java - maven 中没有这样的编译器 'javac'

java - AsyncHttpClient:无法解析补丁 android

c# - 我有一个排序的键/值对列表,想找到与新键相邻的值

c# - 无法从 Action<T> 推断出类型参数,但可以从 Func<T> 推断出类型参数

java - 如何在继承中使用泛型?

python - 将空字符串转换为零

c# - 有没有办法将数据流式传输到 GIT 而不是传递文件名?

java - StringBuilder根据索引输出?