gpt4 book ai didi

Java:将对象转换为泛型

转载 作者:太空狗 更新时间:2023-10-29 22:43:21 26 4
gpt4 key购买 nike

在 Java 中,当从对象转换为其他类型时,为什么第二行会产生与转换相关的警告,而第一行却不会?

void a(Object o) {
Integer i = (Integer) o;
List<Integer> list = (List<Integer>) o;
}

/*Type safety: Unchecked cast from Object to List<Integer>*/

最佳答案

这是因为该对象不会真的被检查为 List<Integer>由于类型删除,在执行时。它实际上只是将其转换为 List .例如:

List<String> strings = new ArrayList<String>();
strings.add("x");
Object o = strings;

// Warning, but will succeeed at execution time
List<Integer> integers = (List<Integer>) o;
Integer i = integers.get(0); // Bang!

参见 Angelika Langer's Java Generics FAQ了解更多信息,特别是 type erasure section .

关于Java:将对象转换为泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4169806/

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