Reputation:
My question is in java we know we can't create dynamic arrays , because when ever we are going to initialize values for array indexes before that we need to define the array size. But we all know that there is a java feature called variable length arguments ,which will create a dynamic array.
Best Ex:public static void main (String... args) So using this variable length arguments we can actually insert any amount of elements for the args array. What is this contradiction ,basic rules of java saying you can't and but another feature enables to do so.
Upvotes: 1
Views: 394
Reputation: 45339
There is no contradiction. What doesn't change is the size of an array that has been created.
So using this variable length arguments we can actually insert any amount of elements for the args array
Yes, (String... args)
allows you to specify any size for the array, just as:
main(String[] args) //called with (new String[]{"a", "b", "c"})
Lets you choose any size for args
. You do the same thing by calling main(String...)
with
main("a", "b", "c")
What you don't realize is that neither of the resulting arrays can change in size. The size of the array is only dynamic as far as it does not need to be known at compile time, but once created (at runtime), the size of the array cannot be changed.
Upvotes: 0
Reputation: 42541
When it comes to vararg methods, you can think of them as methods that accept an array:
public void f(String... args)
is the same as
public void f(String [] args)
This is merely a syntactic sugar that allows the method defined with varags to be called as:
f("a","b","c")
Instead of creating an array first
But if so, you are supposed to specify the length of array when you create it (outside) this specific function f will accepts arrays of any length in runtime
Upvotes: 0
Reputation: 72389
But we all know that there is a java feature called variable length arguments ,which will create a dynamic array.
No, it won't. It will create an array of a static size, and that static size is defined (in your example) by the number of command line arguments. There's no way to increase or decrease the size of this array after it's created. This is really no different than creating a fixed array of a size you calculate programmatically.
If you want an array of a dynamic (i.e. changing size) then Java doesn't offer that. You'll need to use a list, or another collection, instead.
Upvotes: 1