为什么直接将Arrays.asList()分配给var时会出现AssertionError? [英] Why am I getting an AssertionError when assigning Arrays.asList() to var directly?

查看:158
本文介绍了为什么直接将Arrays.asList()分配给var时会出现AssertionError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解Java 10中的本地变量类型推断

I'm trying to understand local variable type inference in Java 10.


  1. 以下代码在编译和运行时完美运行:

  1. The code below works perfectly during compilation and runtime:

List list1 = Arrays.asList(1L, 2.0F, "3");
var list2 = list1;


  • 但是,此行会引发编译错误:

  • However, this line throws a compilation error:

    var list3 = Arrays.asList(1L, 2.0F, "3");
    




    错误:java:java.lang。 AssertionError:意外的交集类型:java.lang.Object& java.io.Serializable& java.lang.Comparable<?扩展java.lang.Object& java.io.Serializable& java.lang.Comparable<?>>


  • 我真的不明白为什么第二种情况是错误的但不是第一种情况。因为我希望编译器会推断 list1 的类型,并处理 list2 list3 相同。在此先感谢。

    I don't really understand why the 2nd case is wrong but not the 1st case. Because I expect the compiler would infer the type of list1 and treat list2 and list3 the same. Thanks in advance.

    推荐答案

    这是Java 10编译器中的一个错误: https://bugs.openjdk.java.net/browse/JDK-8199910

    This is a bug in Java 10 compiler: https://bugs.openjdk.java.net/browse/JDK-8199910

    只有在使用 -g 标志调用 javac 时才会重现。

    It is only reproduced when javac is called with a -g flag.

    可能的解决方法:


    1. 不要使用 -g flag


      • 如果您使用IDEA:设置→构建,执行,部署→编译器→Java编译器→取消选中生成调试信息

    1. Do not use the -g flag
      • If you use IDEA: Settings → Build, Execution, Deployment → Compiler → Java Compiler → Uncheck "Generate Debugging Info"

    • List< Object> list = Arrays.asList(1L,2.0F,3);

    • var list = Arrays。< Object> asList(1L,2.0F,3);

    • List<Object> list = Arrays.asList(1L, 2.0F, "3");
    • var list = Arrays.<Object> asList(1L, 2.0F, "3");



    UDPATE:



    该错误已在 JDK 10.0.2

    这篇关于为什么直接将Arrays.asList()分配给var时会出现AssertionError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆