本文介绍了Java 三元运算符对泛型类型推断的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public List<String> foo1() {
    List<String> retval = bar();
    if (retval == null)
        return Collections.emptyList();
    else
        return retval;
}

public List<String> foo2() {
    List<String> retval = bar();
    return retval == null ? Collections.emptyList() : retval;
}

为什么 foo1() 编译良好而 foo2() 有错误?(更准确地说类型不匹配:无法从 List 转换为 List")

Why does foo1() compiles fine whereas foo2() has an error? (to be more precise "Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>")

我本以为这两个函数会编译成相同的字节码,所以聪明的编译器应该推断 emptyList()...

I would have thought that both functions would compile to the same bytecode, so a clever compiler should infer the correct type for emptyList()...

推荐答案

在 Java 8 中为我编译很好.

Compiles for me fine in java 8.

Java 的早期版本可能需要更多帮助

Earlier versions of Java might need more help

return retval == null ? Collections.<String>emptyList() : retval;

应该可以.

编辑这是由于 Java 8 类型推断的改进,如此处所述

EDITThis is due to improvements in Java 8 type inference as explained here

http://openjdk.java.net/jeps/101

这里有一个重点介绍的博客:http://blog.jooq.org/2013/11/25/a-lesser-known-java-8-feature-generalized-target-type-in​​ference/

And here's a blog with the highlights: http://blog.jooq.org/2013/11/25/a-lesser-known-java-8-feature-generalized-target-type-inference/

这篇关于Java 三元运算符对泛型类型推断的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:19