使用varargs重载功能 [英] Overloading function using varargs

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

问题描述

这将无法编译:

public class Methods
{

    public static void method(Integer... i)
    {
        System.out.print("A");
    }

    public static void method(int... i)
    {
        System.out.print("B");
    }

    public static void main(String args[])
    {
        method(7);
    }
}

这将编译并运作:

public class Methods
{

    public static void method(Integer i)
    {
        System.out.print("A");
    }

    public static void method(int i)
    {
        System.out.print("B");
    }

    public static void main(String args[])
    {
        method(7);
    }
}

第一个和第二个例子非常相似。首先使用varargs,其次不使用varargs。为什么一个有效,第二个没有。 7是原始的,因此在两种情况下都应该调用第二种方法。这是正常行为吗?

First and second example are very similar. First uses varargs, second not. Why one works, second not. 7 is primitive, so second method should be called in both cases. Is it normal behaviour?

我发现它:
错误报告
堆栈溢出

推荐答案

这是对正在发生的事情的高级非正式总结。

This is a high-level informal summary of what is going on.

首先,varargs语法实际上只是用于传递数组的语法糖。所以方法(7)实际上是要传递一些...的数组。

Firstly varargs syntax is really just syntactic sugaring for passing an array. So method(7) is actually going to pass an array of ... something.

但是一个阵列是什么?这里有两个选项对应于方法的两个重载;即 int [] 整数[]

But an array of what? There are two options here corresponding to the two overloads of the method; i.e an int[] or a Integer[].

如果有两个或更多可能有效的重载(即正确的方法名称,正确的参数数量,可转换值),那么解析过程将选择与需要转换的匹配完全匹配的重载,并抱怨如果只有候选人需要转换。 (这是对规则的大幅简化......参见JLS 第15.12节了解完整的故事...并做好长时间/难以阅读的准备!)

If there are two or more overloads that could work (i.e. right method names, right numbers of arguments, convertible values) then the resolution process will chose the overload that is an exact match over a match that requires conversions, and complain if the only candidates require conversions. (This is a drastic simplification of the rules ... see the JLS section 15.12 for the complete story ... and be prepared for a long / difficult read!)

那么发生了什么你的第一个例子就是它试图在两种方法之间做出决定,这两种方法都需要转换;即 int int [] int 整数[] 。基本上它无法决定使用哪种替代方案。因此,编译错误表明调用是不明确的。

So what is happening in your first example is that it is trying to decide between two methods that both require conversions; i.e. int to int[] versus int to Integer[]. Basically it cannot decide which alternative to use. Hence a compilation error that says that the call is ambiguous.

如果您将varargs调用更改为通过显式<$ c $的调用c> Integer [] 或 int [] ,您现在可以完全匹配两个重载中的一个...并且上面的规则说这不是含糊不清的。

If you change the varargs call to a call passing an explicit Integer[] or int[], you now get an exact match to one of the two overloads ... and the rules above say that this is not ambiguous.


我理解为:7是原始的,所以它应该转换为数组 - int []

问题是 7 可以 转换为整数[] ...通过自动装箱首先 int

The problem is that 7 can also be converted to an Integer[] ... by auto-boxing the int first.

这篇关于使用varargs重载功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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