Is there a way to clear a string array on initialization?
If i do
String [] foo = new String[100];
All 100 elements are set to "null" - is there a way to rewrite that initialization to make it all "" ?
| SitePoint Sponsor |
Is there a way to clear a string array on initialization?
If i do
String [] foo = new String[100];
All 100 elements are set to "null" - is there a way to rewrite that initialization to make it all "" ?





or you can use the Arrays class
http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#fill(java.lang.Object[],%20java.lang.Object)
Code:String [] s = new String[100]; java.util.Arrays.fill(s,"");
Thank you, I guess there's no way to initialize it with a default value in a bulk fashion huh, explains why I couldn't find it on google either.





To me, I wouldn't initialize to "" if I have to loop through entire array to set that. I don't know what your business logic is but I rather do
if (strArr[i] == null)
System.out.println("empty")
else
System.out.println(strArr[i])
This is my guess but they are trying to help you optimize the memory usage. So by doing String[100], it creates 100 reference to a String Class. Not an instance of String Class. So, in case you only use 50 then other half will not be loaded into memory. Anyways, if possible I'd avoid this.





Good point, typically I don't use arrays anyway, better to use an ArrayList.This is my guess but they are trying to help you optimize the memory usage. So by doing String[100], it creates 100 reference to a String Class. Not an instance of String Class. So, in case you only use 50 then other half will not be loaded into memory. Anyways, if possible I'd avoid this.
Bookmarks