可变参数函数的歧义 [英] Variable argument function ambiguity

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

问题描述

   public static void main(String[] args) {
       System.out.println(fun(2,3,4));
     }
   static int fun(int a,int b,int c)
   {
     return 1;
   }
   static int fun(int ... a)
   {
     return 0;  
   }

输出: 1

问题: 在上述情况下,为什么函数fun选择第一个函数而不选择第二个函数,选择是在什么基础上进行的,因为无法确定用户实际想要调用哪个函数?

Question: In the above case why does the function fun select the 1st function and not the second.On what basis is the selection done since there is no way to determine which fun the user actually wanted to call ?

推荐答案

基本上,有一个特定呼叫的偏好.除了其他方面,这意味着可以优化少量参数,避免在执行时无意义地创建数组.

Basically there's a preference for a specific call. Aside from anything else, this means it's possible to optimize for small numbers of arguments, avoiding creating an array pointlessly at execution time.

JLS并不清楚,但它在第15.12.2.5节,该部分讨论的是固定Arity方法(如果满足某些条件的话)比另一种方法更具体-并且在这种情况下也是如此.基本上,它是更具体的,因为对于argargs方法,有更多的有效的调用,就好像有相同数量的参数,但参数类型本身更通用.

The JLS doesn't make this very clear, but it's in section 15.12.2.5, the part that talks about a fixed arity method being more specific than another method if certain conditions hold - and they do in this case. Basically it's more specific because there are more calls which would be valid for the varargs method, just as if there were the same number of parameters but the parameter types themselves were more general.

这篇关于可变参数函数的歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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