Greetings Earthlings!
So something that has always bothered me is the outrageous things you need to do to instantiate a generic array (perhaps I’m overreacting).
There are two methods presented EVERYWHERE:
public <T> T[] alloc(Class<T> type, int length) {
return (T[])Array.newInstance(type, length);
}
public <T> T[] alloc(int length) {
return (T[])new Object[length]; //eww, doesn't always work
}
The first way sucks, you need to pass in the class type, which means whatever you have creating the array a user needs to pass in the class type… unnecessary code I daresay!
The second way sucks as well, doesn’t work for me always, it’s annoying. Especially in this case:
public class Foo<X extends Bar> {
public X[] bars;
public Foo(int length) {
bars = (X[])new Object[length];
}
}
NOPE, doesn’t work… since X is at least type Bar, you need to do this:
public class Foo<X extends Bar> {
public X[] bars;
public Foo(int length) {
bars = (X[])new Bar[length];
}
}
Hey that works! Except you still have warnings… I don’t like warnings, hence why I think both of these options suck.
So yesterday an alternative method POPPED in my head… something that is so simple, there’s no casting, nothing ugly…
Somehow I haven’t found ONE website or code example where someone does this, I feel like a god damn explorer (perhaps of the DORA quality).
public class ArrayUtil {
public static <T> T[] alloc(int length, T ... base) {
return Arrays.copyOf( base, length );
}
}
Boom. It’s simple and can even be used in two different ways:
String[] x = ArrayUtil.alloc(4);
String[] y = ArrayUtil.alloc(4, "first", "second");
You know how much ugly code exists in sooo many common libraries that require you to pass in Class so it can create an array? I say they get rid of that silliness.
What say you?