4

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!

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.