有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java泛型函数

我很想知道这是否像我想的那样有效。我确实意识到泛型只是在运行时作为对象结束。这只是我在Eclipse中遇到的一个问题。我在研究Java如何解决集合中泛型的强制转换问题时发现了这个构造。emptyList()。当我从我正在使用的任何界面中抛出一个列表时,我已经厌倦了抑制警告

<T> List<T> emptyList()

在我看来,这就像是在阅读一般演员的任务。例如,这些作品中的任何一个都不会抛出任何类型的铸造错误

List<Object> list = Collections.emptyList();
List<MyObect> list2 = Collections.emptyList();

有人能给我指一下这是如何工作的文档吗。我甚至不知道该叫什么来搜索它


共 (3) 个答案

  1. # 1 楼答案

    它是从指定给它的变量的声明中推断emptyList的类型。如果您希望自己指定,可以使用

    Collections.<MyObject>emptyList();
    

    例如,在方法Arrays.asList中,这可能很有用。该方法允许您编写如下代码:

    List<String> myList = Arrays.asList("a", "b", "c");
    

    但是如果你有一个String[]asList会给你一个List<String[]>而不是一个List<String>。您可以按如下方式覆盖此选项:

    List<String> myList = Arrays.<String>asList(myStringArray);
    

    更多关于泛型方法here中的类型推断

  2. # 2 楼答案

    Java "Type Inference" documentation应该回答与此相关的大多数问题

    Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.

    To illustrate this last point, in the following example, inference determines that the second argument being passed to the pick method is of type Serializable:

    static <T> T pick(T a1, T a2) { return a2; }
    Serializable s = pick("d", new ArrayList<String>());
    

    你可以改变

    List<MyObect> list2 = Collections.emptyList();
    

    List<MyObect> list2 = Collections.<MyObject>emptyList();
    

    为了明确说明<T>应该绑定到<MyObject>,但是对于变量初始值设定项,它应该自动推断

  3. # 3 楼答案

    不确定你到底在问什么。如果您想执行强制转换而不让编译器发出警告,我们可以欺骗编译器来执行

    String string = "hello";
    Number number = bruteCast(string);
    
    @SuppressWarnings("unchecked")
    public static <A,B> B bruteCast(A a)
    {
        return (B)(Object)a;
    }
    

    当然,你必须谨慎地使用它,确保每个对bruteCast()的调用都是正确的