Object processing blurred

I don’t think I understand how varargs handles passed objects:

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");
}

}

results

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

Why does it treat the first set as a string array and the second as a reference to an array of objects?

+3
source share
3 answers

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

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

+2

String[] Object[] . varargs, .

varargs, Object:

    NoSense.someMethod("1", (Object) x);

Object Object[], .

15.12.4.2 JLS:

m k!= n , m k == n , kth- , T [], (e1, ... , en-1, en, ...ek) , (e1, ..., en-1, new T[]{en, ..., ek}).

+1

, varargs. Java , varargs.

Case 1: Only one value is passed to the varargs object []. This value is String []. Java treats it as a special case and directly passes it to an array.

Case 2: Two values ​​are passed to the varargs object []. The first value is of type String [], and the second is of type String. Since more than one value is passed, this is not a special case. Thus, the vargargs parameter is Object [] (just like you defined it), with the first element being the passed array of strings, and the second being the string.

+1
source

Source: https://habr.com/ru/post/1792340/


All Articles