Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of creating array

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!

like image 279
MouseLearnJava Avatar asked Dec 08 '22 11:12

MouseLearnJava


2 Answers

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.

like image 162
duffymo Avatar answered Dec 11 '22 08:12

duffymo


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.

like image 45
masoud Avatar answered Dec 11 '22 08:12

masoud