TheGuyNextDoor
TheGuyNextDoor

Reputation: 7937

Working with Java arrays

/**
 * Testing Arrays
 * @author N002213F
 * @version 1.0
 */
public class JavaArrays {

    public void processNames(String[] arg) {
        //-- patented method, stop, do not read ;)
    }

    public void test() {

        // works fine
        String[] names1 = new String[] { "Jane", "John" };
        processNames(names1);

        // works fine, nothing here
        String[] names2 = { "Jane", "John" };
        processNames(names2);

        // works again, please procced
        processNames(new String[] { "Jane", "John" });

        // fails, why, are there any reasons?
        processNames({ "Jane", "John" });

        // fails, but i thought Java 5 [vargs][1] handles this
        processNames("Jane", "John");
    }
}

Upvotes: 1

Views: 139

Answers (3)

Joey
Joey

Reputation: 354406

processNames({ "Jane", "John" });

This fails, why, are there any reasons?

You didn't specify a type. Java doesn't do type inference here; it expects you to specify that this is a string array. The answers to this question may help for this, too

processNames("Jane", "John"); 

This fails too, but I thought Java 5 varargs handles this

If you want varargs, then you should write your method as such:

public void processNames(String... arg)

Note the ... instead of []. Just accepting an array doesn't entitle you to use varargs on that method.

Upvotes: 9

Fredrik
Fredrik

Reputation: 5839

The third call is incorrect because you cannot create an array like that, you do it like you do in the second call. If you want the final call to succeed you must declare processNames as being a receiver of varargs (see here)

Upvotes: 0

fastcodejava
fastcodejava

Reputation: 41087

On your last line : processNames(String ...args); would have to be written like this for varargs to work.

Upvotes: 1

Related Questions