Reputation: 3197
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!
Upvotes: 4
Views: 133
Reputation: 3347
There is no big difference in these two ways, but the first way is direct, simple, readable, convenient for maintenance, secure.
The second method requires casting the object obtained through reflection. If you have to create object in runtime then use second way, in common use I suggest to use first way.
No need to complicate simple solution just to look better.
Upvotes: 2
Reputation: 5648
Since you know that you want to create 2d string array
, so the first way is enough
But if the component type is not known until runtime (you don't know if you want this array string or int or ...) , so it prefer to use the second way
Object obj=Array.newInstance(Class.forName(c), n);// Here "c" variable will
// known through the run time
see this example to understand what i say
Upvotes: 3
Reputation: 56549
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.
Upvotes: 4
Reputation: 658
I think there is no difference between the first way and the second, although the first way is more readable than the second, and the second shows that you have a good knowledge of what you are doing.
Upvotes: 0
Reputation: 309008
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.
Upvotes: 5