I have seen different approaches to define a static array in Java. Either:
我见过用Java定义静态数组的不同方法。:
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)?
什么是更好的方式(表现明智)?
2 个解决方案
#1
96
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!
#2
8
Nope, no difference. It's just syntactic sugar. Arrays.asList(..)
creates an additional list.
不,没有区别。只是语法糖。aslist(..)创建一个附加的列表。
#1
96
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!
#2
8
Nope, no difference. It's just syntactic sugar. Arrays.asList(..)
creates an additional list.
不,没有区别。只是语法糖。aslist(..)创建一个附加的列表。