栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中方法重载中的Varargs

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/486108.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号