2

Right now I have the following code:

String[] values = {str1, str2};
Utils.myMethod(values);

I would like to know if there is a way to do this all in one line. I've tried:

Utils.myMethod({str1, str2});

But that doesn't work. Thanks in advance.

3 Answers 3

11

You need to specify the type of the array explicitly. It is not inferred. Hence the following is valid,

Utils.myMethod(new String[] {str1, str2}); 
Sign up to request clarification or add additional context in comments.

4 Comments

...and in case you want to work with Lists and want to initialize that list with values without much writing, use this: Utils.myMethod(Arrays.asList(new String[] {str1, str2}));
You can make it simple further: Utils.myMethod(Arrays.asList(str1, str2)); (with Java 1.5 or above since it is a vararg method)
Damnit, that's what i meant. C+P from OP's post made my skill look horrible. I don't deserve to be called a Nerd. You'll find me outside.
@Marithmu it's a lot more verbose than that. here's the required code: Utils.myMethod((String[]) Arrays.asList(str1, str2).toArray());
4

If you own the method in question, consider using the varargs syntax and declaring it like this:

void myMethod(String... args) {

Then, you can call it like this

Utils.myMethod(str1, str2);

Then let the compiler put the array together for you!

Comments

0

Well, you can always rewrite your method to use varargs. This way, you could write

Utils.myMethod(str1, str2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.