模糊的varargs方法 [英] Ambiguous varargs methods

查看:95
本文介绍了模糊的varargs方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个无法编译的代码示例:

Here's a code example that doesn't compile:

public class Test {
    public static void main(String[] args) {
        method(1);
    }

    public static void method(int... x) {
        System.out.println("varargs");
    }

    public static void method(Integer... x) {
        System.out.println("single");
    }
}

有人能告诉我这些方法不明确的原因?提前谢谢。

Can someone tell me the reason why these methods are ambiguous ? Thank you in advance.

推荐答案

考虑方法签名

public static void foo(int a)

public static void foo(Integer a)

在装箱和拆箱之前,调用 foo(1)不会有歧义。为确保与早期版本的Java兼容,调用仍然是明确的。因此,重载决策的第一阶段不允许装箱,取消装箱或变量arity调用,这些都是同时引入的。变量arity调用是指通过为最后一个参数(而不是数组)传递一系列参数来调用varargs方法。

Before boxing and unboxing, the call foo(1) would not have been ambiguous. To ensure compatibility with earlier versions of Java, the call remains unambiguous. Therefore the first phase of overload resolution does not allow for boxing, unboxing, or variable arity invocation, which were all introduced at the same time. Variable arity invocation is when you call a varargs method by passing a sequence of parameters for the last argument (rather than an array).

然而<$ c $的分辨率c>方法(1)对于您的方法签名允许装箱和拆箱,因为两种方法都需要变量arity调用。由于允许拳击,两个签名都适用。通常,当两个过载应用时,选择最具体的过载。但是,您的签名都不比其他签名更具体(因为 int Integer 都不是另一个的子类型) 。因此,调用方法(1)是不明确的。

However the resolution of method(1) for your method signatures allows for boxing and unboxing because both methods require a variable arity invocation. Since boxing is allowed, both signatures apply. Normally when two overloadings apply, the most specific overloading is chosen. However neither of your signatures is more specific than the other (because neither int nor Integer is a subtype of the other). Therefore the call method(1) is ambiguous.

您可以通过传递 new int [] {1} 而不是。

You can make this compile by passing new int[]{1} instead.

这篇关于模糊的varargs方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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