如何初始化静态数组? [英] How to initialize a static array?

查看:158
本文介绍了如何初始化静态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了不同的方法来定义Java中的静态数组。或者:

I have seen different approaches to define a static array in Java. Either:

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

...或者仅

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

,或作为列表

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!

这篇关于如何初始化静态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆