Java中方法重载中的Varargs

Java中方法重载中的Varargs,第1张

Java中方法重载中的Varargs

您可以

Widen
Box
,但你不能两者都做,除非你是
boxing and widening
Object
(一个int,整数(拳击),然后整型
对象(加宽)是合法的,因为每个类的子类
Object
,所以它有可能Integer被传递到Object参数)

同样,

int
to
Number
也是合法的
(int-> Integer-> Number)
,因为
Number
是它的超类
Integer

让我们在您的示例中看到以下内容:

public static void test(Integer...i)public static void test(Float...f)

当选择Boxing,Widening和Var-args组合在一起时,选择某些重载方法时要遵循以下规则:-

  1. 基本扩展使用smallest可能的方法参数
  2. 包装器类型无法扩展为其他包装器类型
  3. 您可以将Box从int更改为Integer,然后将其扩展为Object,但不能将其扩展为Long。
  4. 加宽节拍,搏击节拍可变参数。
  5. 您可以先装箱,然后加宽(int可以Object通过变成Integer)
  6. 您无法加宽,然后Box(int不能变成Long)
  7. 您不能将var-args与扩大或装箱结合使用

因此,根据上述给定规则:

当您将两个整数传递给上述函数时,

  • 根据规 则3,必须先将其放入Widened,然后再Boxed放入Long,根据规则5这是非法的(您不能先加宽,然后再加上Box)。

  • 此,将其装箱以存储在

    Integervar-args
    中。

但是在第一种情况下,您具有具有var-args原始类型的方法:

public static void test(int...i)public static void test(float...f)

Then

test(1, 2)
can invoke both the methods (Since neither of them is more
suitable for
rule 1
to apply) : -

  • In first case it will be
    var-args
  • In second case, it will be Widening and then Var-args (which is allowed)

Now, when you have methods with exactly one int and one flost: -

public static void test(int i)public static void test(float f)

Then on invoking using

test(1)
, rule 1 is followed, and smallest possible
widening (i.e. the
int
where no widening is needed at all) is chosen. So 1st
method will be invoked.

For more information, you can refer to

JLS - Method InvocationConversion



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5478247.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存