简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM