Reputation: 1375
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
?
Upvotes: 0
Views: 655
Reputation: 834
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"));
}
Upvotes: 1
Reputation: 75062
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"};
Upvotes: 4