Reputation: 295
Is there any way to check if an array has already been set to a length in Java?
In my case, I have a recursive method, and in the first iteration of the method, I want the array to have the length of a variable n. However, after the first recursion of the method, I don't want the array to be reassigned a new size.
Additionally, I don't know what the size should be until the first iteration of the method.
Thanks!
Upvotes: 0
Views: 150
Reputation: 764
The Array Reference Variable Would be NULL until you assign to it.
You cannot create an Array Object without a lenght; if you want that, maybe you should create a ArrayList, and you can add objects to it without care about the size.
If you just want to see the lenght of your Array; after CREATE, do this:
public static void main (String[] args){
String[] x = new String[2]; // you cannot create here without a lenght, you MUST set
System.out.println(x.length);
}
OUTPUT: 2
Upvotes: 0
Reputation: 393856
The array variable would be null until you assign an instance to it. Once an instance is assigned, it will have a fixed length. Therefore, a simple null check would suffice.
Upvotes: 4