Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varags Object Handling Oddness

I don't think I understand how varargs is handling objects being passed in:

public class NoSense {

public static void someMethod(String a, Object... things) {

    System.err.println("a->" + a);

    System.err.println(things.getClass().getName());

    for (Object object : things) {
        System.err.println("thing->" + object);
    }


}


public static void main(String[] args) {
    String[] x = new String[] { "what", "is", "up?" };
    NoSense.someMethod("1", x);
    NoSense.someMethod("2", x, "extra");
}

}

The results are

a->1
[Ljava.lang.String;
thing->what
thing->is
thing->up?
a->2
[Ljava.lang.Object;
thing->[Ljava.lang.String;@4d20a47e
thing->extra

Why would it treat the first set as a string array and the second as an object array reference?

like image 811
h1d3m3 Avatar asked May 29 '26 12:05

h1d3m3


1 Answers

To maintain backwards compatibility, varargs is the last thing the compiler does to try to resolve a method call. Because the call NoSense.someMethod("1", x); can be resolved as someMethod(String a, Object[] things), it is resolved as such. It can do this because array types are covariant.

The call NoSense.someMethod("2", x, "extra"); however, can not be resolved as someMethod(String a, Object[] things), and therefore uses varargs to create a new Object[]{x, "extra"}, which is then passed as the things parameter.

like image 65
ILMTitan Avatar answered May 31 '26 07:05

ILMTitan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!