gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:35 24 4
gpt4 key购买 nike

以下有什么区别?

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com