Is there a more convenient way to initialize an array of objects than doing this?
SomeClass[] someArray = new SomeClass[100];
//...
for (int i = 0; i < someArray.length; i++) {
someArray[i] = new SomeClass();
}
// ...
Use Arrays.fill()
String[] stringArray = new String[100];
Arrays.fill(stringArray, "");
It's not any faster since it iterates over the array just like you did, but it is more convenient.
Arrays.fill() code
public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
rangeCheck(a.length, fromIndex, toIndex);
for (int i=fromIndex; i<toIndex; i++)
a[i] = val;
}
Because of the immutability of String
in Java, your question is a bit strange. The primary thrust suggests you are looking for this:
String[] arr = new String[100];
Arrays.fill(arr, new String());//Array utility
However, this does not actually net you anything, because you will have to effectively create a new String
object whenever you replace one of those array items with a different String. This means that the act of creating a new String()
is redundant and therefore less efficient.
This begs the question: why are you doing this? Is it to ensure that there is a valid object being returned? Or that the object in the array is actually a String
? If the latter, make use of generics:
List<String> arr = new ArrayList<String>();
This solves the same problem and nets you benefits of object-orientation. It is generally recommended you stay away from primitive arrays if you can: object-based arrays are far more usable, leading to cleaner code and often more efficient programs.
If you are using a mutable type, and the point of pre-filling is to ensure that an object exists when it's retrieved from the array, the best way to handle this is to actually use exceptions on the receiving end, for two reasons: the first being that you save memory by not allocating memory before you actually need it (and all the attendant savings that go along with that) and the second being that there is little stopping an array from having an element set to null
, so you have to check anyway:
try {
SomeObject myObj = arr.get(idx);
myObj.doSomethingFun();//will fail if this is null!
} catch (NullPointerException e) {
//do something intelligent like return a fail case.
}
Note that while exceptions carry overhead if they catch an actual error, they have no overhead until that point. For this reason you don't want to use them for flow-of-control, but you do want to use them (more than you probably do) to catch edge cases that don't make sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With