Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a static array?

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)?

like image 555
Jeremy S. Avatar asked Aug 08 '11 09:08

Jeremy S.


People also ask

How do you initialize a static array of objects in Java?

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.

How do you declare an array statically?

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.


1 Answers

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! 
like image 120
dogbane Avatar answered Sep 21 '22 19:09

dogbane