I am trying to create array using the following 2 ways:
WAY#1-->
// 1-D String Array
String[] strs1 = new String[8];
// 2-D String Array
String[][] array1 = new String[8][8];
WAY#2-->
// 1-D String Array
String[] strs1 = (String[]) Array.newInstance(String.class, 8);
// 2-D String Array
String[][] array2 = (String[][]) Array.newInstance(String.class, 8, 8);
What's the difference between the above 2 ways for creating arrays ? *Which one is better?* Please help me with this question. Thanks in advance!
I've never seen the second way used since I began writing Java in 1998. I haven't compared the byte code to see if they generate the same stuff, but I'd say the second is less readable, less common, and more of a head scratcher.
Do the simple thing: prefer #1.
The second way usually is useful for generic or run-time array construction, for example:
class Stack<T> {
public Stack(Class<T> clazz,int capacity) {
array=(T[])Array.newInstance(clazz,capacity);
}
private final T[] array;
}
For simple and non generic arrays like yours, you should not use this long and unreadable way. It's just a long equivalent of first one.
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