0

In my main method I have the command below:

if (args.length == 0) // if no command line argument is given
    args.addAll(Arrays.asList("Hello","world"); // error

And there's an error says:

Cannot invoke addAll() on the array type String[]

How do I add multiple elements to args?

1
  • You're missing a bracket to close args.addAll( Commented Mar 7, 2016 at 1:36

2 Answers 2

4

I guess you cannot do such a thing. To append elements to array (not ArrayList or other Collections), create new array and copy elements in old array and elements to append.

In this case, you can simply assign new array with default elements like this:

if (args.length == 0) // if no command line argument is given
    args = new String[]{"Hello","world"};
Sign up to request clarification or add additional context in comments.

Comments

1

The function you're trying to invoke is used by the List objects, not arrays. If you want to work with List, which is easier to use when it comes to add data, try :

List<String> list = new ArrayList<String>(Arrays.asList(args));
list.addAll(Arrays.asList("Hello","world"));

This method will happen them no matter what. if you only want to append them if ags is empty, then use

if (args.length == 0) // if no command line argument is given
{
    List<String> list = new ArrayList<String>(Arrays.asList(args));
    list.addAll(Arrays.asList("Hello","world"));
}

4 Comments

Actually, that won't work. Arrays.asList returns a List backed by an array; you cannot add to it or remove from it. But you can do new ArrayList<String>(Arrays.asList(args)). Also, Collections.addAll is preferred over addAll(Arrays.asList(…)).
Oh, okay, editing that. Didn't know about it, and it somehow didn't show any error in my IDE, thanks
I am accepting Mike's solution since it does not require an additional List<String> object, but thanks.
No problem, I agree with you on that one. I didn't see immediatly that args was supposed to be empty. His answer fits the problem, mine doesn't

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.