I have seen different approaches to define a static array in Java. Either:
String[] suit = new String[] { "spades", "hearts", "diamonds", "clubs" };
...or only
String[] suit = { "spades", "hearts", "diamonds", "clubs" };
or as a List
List suit = Arrays.asList( "spades", "hearts", "diamonds", "clubs" );
Is there a difference (except for the List definition of course)?
What is the better way (performance wise)?
class TestClass { static { arr[0] = "Hi"; arr[1] = "Hello"; arr[2] = "How are you?"; } .... } Show activity on this post. If you want to avoid using a new Object, you might use a Map instead of an array. Note that the first value (1, 2, etc) would always have to be unique though.
To declare a statically allocated array, which you do not have to do for this activity, just declare the type of the array elements and indicate that it is an array by putting []s containing the size after the array variable's name. The size of the array must be specified as either an integer or an integer constant.
If you are creating an array then there is no difference, however, the following is neater:
String[] suit = { "spades", "hearts", "diamonds", "clubs" };
But, if you want to pass an array into a method you have to call it like this:
myMethod(new String[] {"spades", "hearts"}); myMethod({"spades", "hearts"}); //won't compile!
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