gpt4 book ai didi

Java 泛型 - 冗余类型初始化

转载 作者:行者123 更新时间:2023-12-01 11:27:40 26 4
gpt4 key购买 nike

我在其他地方找不到这个确切问题的答案,但如果重复,我深表歉意。

我通常会看到像这样完成的泛型初始化,类型参数位于引用类型旁边,以及作为对象声明:

Box<Integer> integerBox = new Box<Integer>();

或者,在“简写”方法中(自 Java 7 起),使用菱形:

Box<Integer> integerBox = new Box<>();

但是,我注意到省略对象声明旁边的参数类型后代码仍然有效,如下所示:

Box<Integer> integerBox = new Box();

怎么会呢?这是编译器的魔法吗(顺便说一句,我正在使用 NetBeans)。

提前致谢。

最佳答案

这个:

Box<Integer> integerBox = new Box();

将原始的Box分配给integerBox,绕过泛型类型检查。虽然在这种情况下看起来不错,但当你有类似的东西时就不太好了

List<String> strings = Arrays.asList("a", "b", "c");
...
List<Integer> integers = new ArrayList(strings);

如果你这样做

List<Integer> integers = new ArrayList<>(strings);

然后编译器将检测类型不匹配。

关于Java 泛型 - 冗余类型初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689784/

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