0

I would like to set the items in an array of Strings in the parameter of a method.

So if I have an array, public String[] messages;

Then I have a method, public void setMessages(),

I want to be able to use the parameters to set the items in the array, like this:

public void setMessages(String[] messages) {
   this.messages = messages;
}

setMessages("Message 1", "Message 2", "Message 3");

And then the array has those three strings in it. How could I do something like this, because that obviously doesn't work?

2 Answers 2

2

Your setMessages method accepts an array and not three String parameters as mentioned here:

public void setMessages(String[] messages)

So you need to pass an array to it. Simply replace

setMessages("Message 1", "Message 2", "Message 3");

with

setMessages(new String[] {"Message 1", "Message 2", "Message 3"});
Sign up to request clarification or add additional context in comments.

1 Comment

+1 I like new String[]{} better than varargs. I recently got burned with varargs causing an ambiguous signature.
-1

Change your method signature to accept messages as a variable-length argument, or vararg for short.

public void setMessages(String... messages) {
    this.messages = messages;
}

What are varargs?

  • They are equivalent to an array of the same type (so above, you still have a String[]).
  • They allow any arbitrary number of values to be placed into it.
  • They do not require the caller to create a new instance of an array to pass in (which would look like this):

     setMessages(new String[] {"Message 1", "Message 2", "Message 3"});
    

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.