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

Java中方法重载中的Varargs

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

Java中方法重载中的Varargs

You can either

Widen
or
Box
but you cannot do both, unless you are
boxingand widening
to
Object
(An int to Integer(Boxing) and then Integer to
Object(Widening) is legal, since every class is a subclass of
Object
, so it
is possible for
Integer
to be passed to
Object
parameter)

Similarly an

int
to
Number
is also legal (int -> Integer -> Number) Since
Number is the super class of
Integer
it is possible.

Let’s see this in your example: -

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

There are some rules that are followed when selecting which overloaded method
to select, when Boxing, Widening, and Var-args are combined: -

  1. Primitive widening uses the
    smallest
    method argument possible
  2. Wrapper type cannot be widened to another Wrapper type
  3. You can Box from int to Integer and widen to Object but no to Long
  4. Widening beats Boxing, Boxing beats Var-args.
  5. You can Box and then Widen (An
    int
    can become
    Object
    via
    Integer
    )
  6. You cannot Widen and then Box (An
    int
    cannot become
    Long
    )
  7. You cannot combine var-args, with either widening or boxing

So, based on the above given rules: -

When you pass two integers to above functions,

  • according to rule 3, it will have to be first
    Widened
    and then
    Boxed
    to fit into a
    Long
    , which is illegal according to rule 5 (You cannot Widen and then Box).
  • So, it is Boxed to store in
    Integer
    var-args.

But in first case, where you have methods with
var-args
of primitive types:

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/437492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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