How to initialize a static array?

JavaArraysStaticPlaying Cards

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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!

Solution 2 - Java

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy S.View Question on Stackoverflow
Solution 1 - JavadogbaneView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow