How do I declear an array of unknow size? Can I do the following where getNames() will return an array of Strings? Thanks!
String[] names = new String[0];
names = getNames();
Printable View
How do I declear an array of unknow size? Can I do the following where getNames() will return an array of Strings? Thanks!
String[] names = new String[0];
names = getNames();
You can either set the array length to a large number or use an ArrayList instead. Arrays have a fixed length so if you don't know the size when you're creating it there's no way to change it unless you transfer it to another array.
Using ArrayList is easier because you can just append a new item to the end and the length can increase as needed.
I have to use array because the method getName() returns an array of string. Will the way I mentioned above works?
Why even initialize it? Why don't you just do something like this
Code:String[] names = getNames();
The reason I have to init it first is because the way I am using. If I do "String[] names = getNames();", the scope of "names" will not allow me to have the "return statement" at the end of the method.
String [] names = new String[0];
try {
....
names = getNames();
...
} catch (Throwable e)
...
}
return names;
The problem with initializing to a default value is it sounds like you are never going to use it and even if you do, its only because getNames() errored. You should still have the scope for names inside the method, so a return is possible.
Sounds like you should do this then....
Code:String[] names = null;
try {
names = getNames();
} catch (Throwable e) {
e.printStackTrace();
}
if (names != null) {
....//Processing or doing whatever
}
return names;
Great! Thanks! I will try it out.