如何初始化静态数组?


70

我已经看到了在Java中定义静态数组的不同方法。要么:

String[] suit = new String[] {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

...或仅

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

或作为 List

List suit = Arrays.asList(
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
);

有区别吗(当然除了List定义)?

有什么更好的方法(明智的选择)?

Answers:


108

如果创建数组,则没有什么区别,但是,以下内容更整洁:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

但是,如果要将数组传递给方法,则必须这样调用它:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.